import pandas as pd
import numpy as np
import requests
import json
import time
import random
from datetime import datetime, timedelta
from market_state_analyzer import MarketStateAnalyzer
from divergence_detector import DivergenceDetector

# 解决SQLite驱动问题
try:
    import pysqlite3 as sqlite3
    import sys
    sys.modules['sqlite3'] = sqlite3
except ImportError:
    pass

# Python 3.6兼容性处理 - 在导入yfinance之前修复TypedDict问题
import sys
if sys.version_info < (3, 8):
    import typing
    if not hasattr(typing, 'TypedDict'):
        try:
            from typing_extensions import TypedDict
            typing.TypedDict = TypedDict
        except ImportError:
            # 创建一个简单的TypedDict替代品
            class TypedDict(dict):
                def __init_subclass__(cls, **kwargs):
                    pass
                    
                def __new__(cls, *args, **kwargs):
                    return dict(*args, **kwargs)
            
            typing.TypedDict = TypedDict

import yfinance as yf

# 新版本的yfinance不再支持自定义requests session
# 它会自动使用curl_cffi来处理请求头和反爬虫机制

try:
    from scipy.stats import linregress
except ImportError:
    # 如果scipy不可用，使用numpy实现线性回归
    def linregress(x, y):
        n = len(x)
        mean_x = np.mean(x)
        mean_y = np.mean(y)
        slope = np.sum((x - mean_x) * (y - mean_y)) / np.sum((x - mean_x) ** 2)
        return type('Result', (), {'slope': slope})()

import warnings
warnings.filterwarnings('ignore')

class StockAnalyzer:
    def __init__(self, symbol, period="6mo"):
        """
        初始化股票分析器
        :param symbol: 股票代码
        :param period: 数据周期，默认6个月
        """
        self.symbol = symbol
        self.period = period
        self.data = None
        self.macd_data = None
        self.rsi_data = None
        self.market_state_analyzer = None
        self.divergence_detector = DivergenceDetector()
        
        # 重试配置
        self.max_retries = 3  # 减少重试次数
        self.base_delay = 1   # 减少基础延迟
        self.max_delay = 10   # 减少最大延迟
    
    def _generate_smart_symbol_variants(self, clean_symbol):
        """
        智能生成股票代码变体，根据代码特征添加正确的市场后缀
        6字头 -> .SS (上交所)
        0字头和3字头 -> .SZ (深交所)
        4字头和8字头 -> .BJ (北交所)
        """
        symbol_variants = []
        
        # 如果已经包含市场后缀，直接返回
        if '.' in clean_symbol:
            market_suffix = clean_symbol.split('.')[-1]
            if market_suffix in ['SZ', 'SS', 'SHE', 'SHA', 'HK', 'TO', 'BJ']:
                # 已经是标准格式，直接返回
                return [clean_symbol]
        
        # 针对纯数字代码的智能处理
        if clean_symbol.isdigit():
            if len(clean_symbol) == 6:
                # 6位数字代码，根据第一位数字判断交易所
                first_digit = clean_symbol[0]
                if first_digit == '6':  # 上交所
                    symbol_variants.append(f"{clean_symbol}.SS")
                elif first_digit in ['0', '3']:  # 深交所
                    symbol_variants.append(f"{clean_symbol}.SZ")
                elif first_digit in ['4', '8']:  # 北交所
                    symbol_variants.append(f"{clean_symbol}.BJ")
                else:  # 其他情况，尝试最常用的格式
                    symbol_variants.append(f"{clean_symbol}.SZ")
            elif len(clean_symbol) == 5:
                # 5位数字代码，可能是港股
                symbol_variants.append(f"{clean_symbol}.HK")
            elif len(clean_symbol) == 4:
                # 4位数字代码，可能是港股
                symbol_variants.append(f"{clean_symbol}.HK")
            # 不再添加原始数字代码作为变体
        
        # 如果没有生成任何变体，添加原始代码作为备选
        if not symbol_variants:
            symbol_variants.append(clean_symbol)
        
        return symbol_variants

    def _fetch_data_with_retry(self, symbol):
        """
        使用智能重试机制获取股票数据
        """
        def fetch_yfinance_data():
            stock = yf.Ticker(symbol)
            
            # 只尝试配置的周期，不再尝试多个周期
            try:
                data = stock.history(period=self.period)
                if not data.empty and len(data) >= 10:  # 至少需要10个数据点
                    self.data = data
                    self.symbol = symbol  # 更新为成功的symbol
                    return data
            except Exception as e:
                if "Rate limited" in str(e) or "Too Many Requests" in str(e):
                    raise e  # 重新抛出API限制错误，让重试机制处理
                # 对于其他错误，快速失败
                return None
            
            return None
        
        # 使用智能重试机制，但限制重试次数和时间
        result = self._smart_retry_with_backoff(fetch_yfinance_data)
        
        if result is not None and not result.empty:
            print(f"✅ 成功获取股票 {symbol} 的数据 ({len(result)} 个数据点)")
            return True
        
        return False

    def _smart_retry_with_backoff(self, func, *args, **kwargs):
        """
        智能重试机制，使用指数退避和随机抖动
        """
        for attempt in range(self.max_retries):
            try:
                result = func(*args, **kwargs)
                if result is not None and not (hasattr(result, 'empty') and result.empty):
                    return result
            except Exception as e:
                error_str = str(e).lower()
                
                # 检查是否是API限制错误
                if any(keyword in error_str for keyword in ['rate limit', 'too many requests', '429', 'quota', 'throttle']):
                    if attempt < self.max_retries - 1:
                        # 计算延迟时间：指数退避 + 随机抖动
                        delay = min(self.base_delay * (2 ** attempt), self.max_delay)
                        jitter = random.uniform(0.5, 1.5)  # 随机抖动因子
                        total_delay = delay * jitter
                        
                        print(f"⏳ API限制，等待 {total_delay:.1f} 秒后重试 (第 {attempt + 1}/{self.max_retries} 次)...")
                        time.sleep(total_delay)
                        continue
                    else:
                        print(f"❌ 达到最大重试次数，API限制无法解决")
                        raise e
                else:
                    # 非API限制错误，快速失败
                    return None
        
        return None

    def fetch_data(self):
        """
        获取股票数据 - 优化版本，提高匹配效率
        """
        try:
            # 验证股票代码格式
            if not self.symbol or len(self.symbol.strip()) == 0:
                raise ValueError("股票代码不能为空")
            
            # 清理股票代码，去除多余空格
            clean_symbol = self.symbol.strip().upper()
            
            print(f"正在尝试获取股票 {clean_symbol} 的数据...")
            
            # 根据股票代码特征智能判断可能的格式，减少盲目尝试
            symbol_variants = self._generate_smart_symbol_variants(clean_symbol)
            
            # 逐个尝试股票代码变换
            for i, symbol_variant in enumerate(symbol_variants):
                try:
                    if symbol_variant != clean_symbol:
                        print(f"尝试格式: {symbol_variant}")
                    
                    # 使用智能重试机制获取数据
                    success = self._fetch_data_with_retry(symbol_variant)
                    if success:
                        return True
                        
                    # 如果是API限制错误，且不是最后一个变体，尝试下一个
                    # 这样可以避免在第一个变体上浪费太多时间
                    if i < len(symbol_variants) - 1:
                        print(f"跳过 {symbol_variant}，尝试下一个格式...")
                        
                except Exception as e:
                    error_str = str(e).lower()
                    if any(keyword in error_str for keyword in ['rate limit', 'too many requests', '429', 'quota', 'throttle']):
                        print(f"API限制，尝试下一个格式...")
                        continue
                    else:
                        print(f"格式 {symbol_variant} 失败: {str(e)[:100]}...")
                        continue
            
            # 如果所有格式都失败了，尝试备用数据源
            print("🔄 Yahoo Finance失败，尝试备用数据源...")
            if self._try_alternative_data_sources(clean_symbol):
                return True
            
            # 如果所有方法都失败了
            error_msg = f"❌ 无法获取股票 {clean_symbol} 的数据。\n\n"
            error_msg += "🔍 可能的原因：\n"
            error_msg += "  1. 股票代码不正确\n"
            error_msg += "  2. 股票已退市或暂停交易\n"
            error_msg += "  3. 所有数据源都暂时不可用\n\n"
            error_msg += "📝 支持的格式示例：\n"
            error_msg += "  - 美股: AAPL, TSLA, GOOGL, MSFT\n"
            error_msg += "  - A股: 000001.SZ, 600000.SS (或纯6位数字)\n"
            error_msg += "  - 港股: 0700.HK, 0941.HK\n\n"
            error_msg += "💡 建议：\n"
            error_msg += "  - 检查股票代码拼写\n"
            error_msg += "  - 尝试使用不同的代码格式\n"
            error_msg += "  - 稍后重试（可能是临时限制）\n"
            error_msg += "  - 检查网络连接"
            
            raise ValueError(error_msg)
            
        except Exception as e:
            print(f"获取股票数据时出错: {e}")
            return False

            return False

    def _try_alternative_data_sources(self, symbol):
        """
        尝试使用备用数据源获取股票数据
        在实战环境中，不使用模拟数据，直接返回False
        """
        # 在实战环境中，不生成模拟数据
        print("❌ 无法获取股票数据，不使用模拟数据")
        return False

    def calculate_macd(self, short_window=12, long_window=26, signal_window=9):
        """
        计算MACD指标
        :param short_window: 短期EMA窗口，默认12
        :param long_window: 长期EMA窗口，默认26
        :param signal_window: 信号线窗口，默认9
        """
        if self.data is None:
            print("请先获取股票数据")
            return False
        
        # 计算EMA
        short_ema = self.data['Close'].ewm(span=short_window, adjust=False).mean()
        long_ema = self.data['Close'].ewm(span=long_window, adjust=False).mean()
        
        # 计算MACD线和信号线
        macd_line = short_ema - long_ema
        signal_line = macd_line.ewm(span=signal_window, adjust=False).mean()
        
        # 计算MACD柱状图
        macd_histogram = macd_line - signal_line
        
        # 保存数据
        self.macd_data = pd.DataFrame({
            'MACD': macd_line,
            'Signal': signal_line,
            'Histogram': macd_histogram
        }, index=self.data.index)
        
        return True
    
    def detect_macd_crossover(self):
        """
        检测高胜率MACD金叉和死叉，基于四大核心原则：
        1. 核心位置：金叉发生在零轴上方或附近
        2. 共振确认：需要底背离或价格突破阻力位
        3. 量能驱动：必须有成交量明显放大
        4. 时效评估：基于信号的时效性和持续性评判
        
        优化逻辑：确保金叉和死叉不会同时为true，以最近的信号为准
        新增：检测即将形成的金叉信号
        """
        if self.macd_data is None:
            print("请先计算MACD指标")
            return None
        
        # 获取最近的MACD和信号线数据
        macd_line = self.macd_data['MACD']
        signal_line = self.macd_data['Signal']
        histogram = self.macd_data['Histogram']
        
        # 检测金叉和死叉，并确定最近的信号
        golden_cross = self._detect_golden_cross(macd_line, signal_line, histogram)
        death_cross = self._detect_death_cross(macd_line, signal_line, histogram)
        
        # 新增：检测即将形成的金叉
        pre_golden_cross = self._detect_pre_golden_cross(macd_line, signal_line, histogram)
        
        # 确保金叉和死叉不会同时为true - 以最近的信号为准
        if golden_cross['detected'] and death_cross['detected']:
            # 比较两个信号的日期，保留最近的
            if golden_cross['date'] >= death_cross['date']:
                # 金叉更近，清除死叉
                death_cross = {
                    'detected': False,
                    'date': None,
                    'risk_level': 'low',
                    'risk_score': 0,
                    'position_risk': 0,
                    'momentum_risk': 0,
                    'volume_risk': 0,
                    'timeliness_risk': 0
                }
            else:
                # 死叉更近，清除金叉
                golden_cross = {
                    'detected': False,
                    'date': None,
                    'quality': 'low',
                    'quality_score': 0,
                    'position_score': 0,
                    'resonance_score': 0,
                    'volume_score': 0,
                    'timeliness_score': 0
                }
        
        # 返回综合结果
        return {
            'golden_cross': golden_cross,
            'death_cross': death_cross,
            'pre_golden_cross': pre_golden_cross,  # 新增：即将金叉信号
            'current_macd': macd_line.iloc[-1],
            'current_signal': signal_line.iloc[-1],
            'current_histogram': histogram.iloc[-1],
            'detected': golden_cross['detected'],  # 保持向后兼容
            'date': golden_cross['date'],
            'quality': golden_cross['quality'],
            'quality_score': golden_cross['quality_score'],
            'position_score': golden_cross['position_score'],
            'resonance_score': golden_cross['resonance_score'],
            'volume_score': golden_cross['volume_score'],
            'timeliness_score': golden_cross['timeliness_score']
        }
    
    def _detect_golden_cross(self, macd_line, signal_line, histogram):
        """
        检测MACD金叉信号并评估其质量
        优化版本：增加容差范围和趋势确认机制，避免过于严格的判断条件
        """
        crossover_detected = False
        crossover_date = None
        crossover_quality = 'low'
        quality_score = 0
        position_score = 0
        resonance_score = 0
        volume_score = 0
        timeliness_score = 0
        
        # 设置容差范围（相对于价格的百分比）
        tolerance_pct = 0.001  # 0.1%的容差
        
        # 从最近的数据开始倒序检查（检查最近30天）
        for i in range(len(macd_line)-1, max(0, len(macd_line)-31), -1):
            if i < 2:  # 需要至少3个数据点进行趋势确认
                continue
                
            # 获取当前和历史数据点
            current_macd = macd_line.iloc[i]
            current_signal = signal_line.iloc[i]
            prev_macd = macd_line.iloc[i-1]
            prev_signal = signal_line.iloc[i-1]
            prev2_macd = macd_line.iloc[i-2]
            prev2_signal = signal_line.iloc[i-2]
            
            # 计算动态容差（基于近期波动性）
            recent_volatility = np.std([current_macd, prev_macd, prev2_macd])
            dynamic_tolerance = max(tolerance_pct * abs(current_signal), recent_volatility * 0.1)
            
            # 优化的金叉判断逻辑：
            # 1. 基本条件：当前MACD > Signal
            # 2. 趋势确认：MACD相对于Signal的趋势在改善
            # 3. 容差处理：允许小幅度的"假突破"
            
            macd_signal_diff_current = current_macd - current_signal
            macd_signal_diff_prev = prev_macd - prev_signal
            macd_signal_diff_prev2 = prev2_macd - prev2_signal
            
            # 检查是否为有效金叉
            is_golden_cross = False
            
            # 方法1：传统严格交叉（保留原有逻辑作为主要判断）
            if (current_macd > current_signal and prev_macd <= prev_signal):
                is_golden_cross = True
                
            # 方法2：容差交叉（处理边界情况）
            elif (macd_signal_diff_current > -dynamic_tolerance and 
                  macd_signal_diff_prev < -dynamic_tolerance):
                # MACD接近或略微穿过信号线，且趋势向上
                macd_trend = current_macd - prev_macd
                signal_trend = current_signal - prev_signal
                if macd_trend > signal_trend:  # MACD上升速度快于信号线
                    is_golden_cross = True
                    
            # 方法3：趋势确认交叉（更可靠的信号）
            elif (macd_signal_diff_current > 0 and 
                  macd_signal_diff_prev <= 0 and 
                  macd_signal_diff_prev2 < macd_signal_diff_prev):
                # 连续改善的趋势确认
                is_golden_cross = True
            
            if is_golden_cross:
                # 额外的信号质量验证
                if self._validate_crossover_quality(macd_line, signal_line, i):
                    crossover_detected = True
                    crossover_date = macd_line.index[i]
                    
                    # 评估金叉质量 - 根据四大原则
                    position_score = self._evaluate_position_quality(macd_line, signal_line, i)
                    resonance_score = self._evaluate_resonance_quality(i)
                    volume_score = self._evaluate_volume_quality(i)
                    timeliness_score = self._evaluate_timeliness_quality(i, 'golden')
                    
                    # 获取动态权重（基于市场状态）
                    if self.market_state_analyzer:
                        market_state = self.market_state_analyzer.analyze_market_state()
                        dynamic_weights = market_state['dynamic_weights']
                        position_weight = dynamic_weights['position']
                        resonance_weight = dynamic_weights['resonance'] 
                        volume_weight = dynamic_weights['volume']
                        timeliness_weight = dynamic_weights['timeliness']
                    else:
                        # 默认权重（如果市场状态分析器不可用）
                        position_weight = 0.35
                        resonance_weight = 0.30
                        volume_weight = 0.20
                        timeliness_weight = 0.15
                    
                    # 综合评分（使用动态权重）
                    quality_score = (position_score * position_weight + resonance_score * resonance_weight + 
                                   volume_score * volume_weight + timeliness_score * timeliness_weight)
                    
                    # 确定质量等级（提高标准）
                    if quality_score >= 80:
                        crossover_quality = 'high'
                    elif quality_score >= 60:
                        crossover_quality = 'medium'
                    else:
                        crossover_quality = 'low'
                    
                    # 找到最近一次金叉后立即退出
                    break
        
        return {
            'detected': crossover_detected,
            'date': crossover_date,
            'quality': crossover_quality,
            'quality_score': quality_score,
            'position_score': position_score,
            'resonance_score': resonance_score,
            'volume_score': volume_score,
            'timeliness_score': timeliness_score
        }
    
    def _detect_death_cross(self, macd_line, signal_line, histogram):
        """
        检测MACD死叉信号并评估其风险程度
        优化版本：增加容差范围和趋势确认机制，避免过于严格的判断条件
        """
        crossover_detected = False
        crossover_date = None
        risk_level = 'low'
        risk_score = 0
        position_risk = 0
        momentum_risk = 0
        volume_risk = 0
        timeliness_risk = 0
        
        # 设置容差范围（相对于价格的百分比）
        tolerance_pct = 0.001  # 0.1%的容差
        
        # 从最近的数据开始倒序检查（检查最近30天）
        for i in range(len(macd_line)-1, max(0, len(macd_line)-31), -1):
            if i < 2:  # 需要至少3个数据点进行趋势确认
                continue
                
            # 获取当前和历史数据点
            current_macd = macd_line.iloc[i]
            current_signal = signal_line.iloc[i]
            prev_macd = macd_line.iloc[i-1]
            prev_signal = signal_line.iloc[i-1]
            prev2_macd = macd_line.iloc[i-2]
            prev2_signal = signal_line.iloc[i-2]
            
            # 计算动态容差（基于近期波动性）
            recent_volatility = np.std([current_macd, prev_macd, prev2_macd])
            dynamic_tolerance = max(tolerance_pct * abs(current_signal), recent_volatility * 0.1)
            
            # 优化的死叉判断逻辑：
            # 1. 基本条件：当前MACD < Signal
            # 2. 趋势确认：MACD相对于Signal的趋势在恶化
            # 3. 容差处理：允许小幅度的"假突破"
            
            macd_signal_diff_current = current_macd - current_signal
            macd_signal_diff_prev = prev_macd - prev_signal
            macd_signal_diff_prev2 = prev2_macd - prev2_signal
            
            # 检查是否为有效死叉
            is_death_cross = False
            
            # 方法1：传统严格交叉（保留原有逻辑作为主要判断）
            if (current_macd < current_signal and prev_macd >= prev_signal):
                is_death_cross = True
                
            # 方法2：容差交叉（处理边界情况）
            elif (macd_signal_diff_current < dynamic_tolerance and 
                  macd_signal_diff_prev > dynamic_tolerance):
                # MACD接近或略微跌破信号线，且趋势向下
                macd_trend = current_macd - prev_macd
                signal_trend = current_signal - prev_signal
                if macd_trend < signal_trend:  # MACD下降速度快于信号线
                    is_death_cross = True
                    
            # 方法3：趋势确认交叉（更可靠的信号）
            elif (macd_signal_diff_current < 0 and 
                  macd_signal_diff_prev >= 0 and 
                  macd_signal_diff_prev2 > macd_signal_diff_prev):
                # 连续恶化的趋势确认
                is_death_cross = True
            
            if is_death_cross:
                # 额外的信号质量验证
                if self._validate_crossover_quality(macd_line, signal_line, i):
                    crossover_detected = True
                    crossover_date = macd_line.index[i]
                    
                    # 评估死叉风险
                    position_risk = self._evaluate_death_position_risk(macd_line, signal_line, i)
                    momentum_risk = self._evaluate_momentum_risk(i)
                    volume_risk = self._evaluate_death_volume_risk(i)
                    timeliness_risk = self._evaluate_timeliness_quality(i, 'death')
                    
                    # 获取动态权重（基于市场状态）
                    if self.market_state_analyzer:
                        market_state = self.market_state_analyzer.analyze_market_state()
                        dynamic_weights = market_state['dynamic_weights']
                        position_weight = dynamic_weights['position']
                        momentum_weight = dynamic_weights['resonance']  # 对于死叉，共振对应动量
                        volume_weight = dynamic_weights['volume']
                        timeliness_weight = dynamic_weights['timeliness']
                    else:
                        # 默认权重（如果市场状态分析器不可用）
                        position_weight = 0.35
                        momentum_weight = 0.30
                        volume_weight = 0.20
                        timeliness_weight = 0.15
                    
                    # 综合风险评分（使用动态权重）
                    risk_score = (position_risk * position_weight + momentum_risk * momentum_weight + 
                                volume_risk * volume_weight + timeliness_risk * timeliness_weight)
                    
                    # 确定风险等级（提高标准）
                    if risk_score >= 80:
                        risk_level = 'high'
                    elif risk_score >= 60:
                        risk_level = 'medium'
                    else:
                        risk_level = 'low'
                    
                    # 找到最近一次死叉后立即退出
                    break
        
        return {
            'detected': crossover_detected,
            'date': crossover_date,
            'risk_level': risk_level,
            'risk_score': risk_score,
            'position_risk': position_risk,
            'momentum_risk': momentum_risk,
            'volume_risk': volume_risk,
            'timeliness_risk': timeliness_risk
        }
    
    def _detect_pre_golden_cross(self, macd_line, signal_line, histogram):
        """
        检测即将形成的MACD金叉信号（优化版）
        重点关注DIFF向上势能的加速度变化，当DIFF的向上加速度开始放大时给予高分
        识别MACD线正在向信号线靠近，且具有强劲向上动量的情况
        """
        pre_cross_detected = False
        convergence_strength = 0
        days_to_cross = 999  # 预估多少天后可能金叉
        convergence_quality = 'low'
        acceleration_bonus = 0
        
        try:
            # 检查最近7天的数据（增加数据量以更好计算加速度）
            if len(macd_line) < 7:
                return {
                    'detected': False,
                    'convergence_strength': 0,
                    'days_to_cross': 999,
                    'quality': 'low',
                    'acceleration_analysis': {}
                }
            
            # 获取最近几天的数据
            recent_macd = macd_line.iloc[-7:]
            recent_signal = signal_line.iloc[-7:]
            recent_diff = recent_macd - recent_signal
            
            # 当前MACD必须在信号线下方（否则已经金叉了）
            current_diff = recent_diff.iloc[-1]
            if current_diff >= 0:
                return {
                    'detected': False,
                    'convergence_strength': 0,
                    'days_to_cross': 999,
                    'quality': 'low',
                    'acceleration_analysis': {}
                }
            
            # 核心优化：计算DIFF和DEA的加速度分析
            acceleration_analysis = self._calculate_diff_dea_acceleration(recent_macd, recent_signal, lookback_days=5)
            
            # 检查收敛趋势：差值是否在缩小
            diff_trend = []
            for i in range(1, len(recent_diff)):
                diff_change = recent_diff.iloc[i] - recent_diff.iloc[i-1]
                diff_trend.append(diff_change)
            
            # 计算基础收敛强度
            positive_changes = sum(1 for change in diff_trend if change > 0)
            convergence_ratio = positive_changes / len(diff_trend)
            
            # 基于加速度的优化判断逻辑
            acceleration_strength = acceleration_analysis['acceleration_strength']
            momentum_quality = acceleration_analysis['momentum_quality']
            diff_acceleration = acceleration_analysis['diff_acceleration']
            acceleration_trend = acceleration_analysis['acceleration_trend']
            
            # 新的即将金叉判断标准（重点关注加速度）
            is_valid_pre_cross = False
            
            # 方法1：传统收敛判断（保留但降低权重）
            if convergence_ratio >= 0.6:
                is_valid_pre_cross = True
                base_strength = convergence_ratio * 60  # 降低基础权重
            
            # 方法2：加速度驱动判断（新增，高权重）
            elif acceleration_strength >= 70 and diff_acceleration > 0:
                # DIFF向上加速度强劲，即使收敛比例不高也认为是有效信号
                is_valid_pre_cross = True
                base_strength = 70
            
            # 方法3：爆发性动量判断（新增，最高权重）
            elif momentum_quality in ['explosive', 'strong'] and acceleration_trend > 0.002:
                # 检测到爆发性或强劲动量，且加速度趋势向上
                is_valid_pre_cross = True
                base_strength = 80
            
            if is_valid_pre_cross:
                pre_cross_detected = True
                
                # 计算增强的收敛强度（融合加速度因子）
                # 基础强度 + 加速度奖励 + 动量质量奖励
                acceleration_bonus = self._calculate_acceleration_bonus(
                    acceleration_strength, 
                    momentum_quality, 
                    diff_acceleration, 
                    acceleration_trend
                )
                
                convergence_strength = min(100, base_strength + acceleration_bonus)
                
                # 基于加速度优化的交叉时间预测
                days_to_cross = self._predict_cross_timing_with_acceleration(
                    current_diff, diff_trend, acceleration_analysis
                )
                
                # 基于加速度的质量评估（重新定义标准）
                convergence_quality = self._evaluate_pre_cross_quality_with_acceleration(
                    convergence_strength, 
                    days_to_cross, 
                    momentum_quality,
                    acceleration_strength
                )
            
            # 额外检查：MACD线斜率是否向上（保留原有逻辑）
            macd_slope = self._calculate_line_slope(recent_macd)
            signal_slope = self._calculate_line_slope(recent_signal)
            
            # 如果MACD上升速度比信号线快，进一步增加收敛强度
            if macd_slope > signal_slope and pre_cross_detected:
                slope_bonus = min(15, (macd_slope - signal_slope) * 100)
                convergence_strength = min(100, convergence_strength + slope_bonus)
            
            return {
                'detected': pre_cross_detected,
                'convergence_strength': convergence_strength,
                'days_to_cross': days_to_cross,
                'quality': convergence_quality,
                'macd_slope': macd_slope,
                'signal_slope': signal_slope,
                'current_gap': abs(current_diff),
                'acceleration_analysis': acceleration_analysis,  # 新增：加速度分析结果
                'acceleration_bonus': acceleration_bonus,  # 新增：加速度奖励分数
                'momentum_quality': momentum_quality,  # 新增：动量质量
                'diff_acceleration': diff_acceleration,  # 新增：DIFF加速度
                'acceleration_trend': acceleration_trend  # 新增：加速度趋势
            }
            
        except Exception as e:
            return {
                'detected': False,
                'convergence_strength': 0,
                'days_to_cross': 999,
                'quality': 'low',
                'acceleration_analysis': {}
            }
    
    def _calculate_acceleration_bonus(self, acceleration_strength, momentum_quality, diff_acceleration, acceleration_trend):
        """
        计算基于加速度的奖励分数
        重点奖励DIFF向上势能加速度放大的情况
        """
        bonus = 0
        
        # 1. 基于加速度强度的奖励
        if acceleration_strength >= 90:
            bonus += 25  # 极强加速度
        elif acceleration_strength >= 80:
            bonus += 20  # 强加速度
        elif acceleration_strength >= 70:
            bonus += 15  # 中等加速度
        elif acceleration_strength >= 60:
            bonus += 10  # 轻微加速度
        
        # 2. 基于动量质量的奖励
        momentum_bonus = {
            'explosive': 20,  # 爆发性动量
            'strong': 15,     # 强劲动量
            'moderate': 10,   # 中等动量
            'weak': 5,        # 弱动量
            'declining': 0    # 衰减动量
        }
        bonus += momentum_bonus.get(momentum_quality, 0)
        
        # 3. 基于DIFF加速度的直接奖励
        if diff_acceleration > 0.01:
            bonus += 15  # 极强向上加速
        elif diff_acceleration > 0.005:
            bonus += 12  # 强向上加速
        elif diff_acceleration > 0.002:
            bonus += 8   # 中等向上加速
        elif diff_acceleration > 0:
            bonus += 5   # 轻微向上加速
        
        # 4. 基于加速度趋势的奖励（加速度是否在放大）
        if acceleration_trend > 0.008:
            bonus += 12  # 加速度快速放大
        elif acceleration_trend > 0.005:
            bonus += 10  # 加速度中等放大
        elif acceleration_trend > 0.002:
            bonus += 8   # 加速度轻微放大
        elif acceleration_trend > 0:
            bonus += 5   # 加速度微弱放大
        
        return min(30, bonus)  # 最大奖励30分
    
    def _predict_cross_timing_with_acceleration(self, current_diff, diff_trend, acceleration_analysis):
        """
        基于加速度优化的交叉时间预测
        """
        try:
            # 获取加速度信息
            diff_acceleration = acceleration_analysis['diff_acceleration']
            diff_velocity_trend = acceleration_analysis['diff_velocity_trend']
            
            # 如果有明显的向上加速度，使用加速度模型预测
            if diff_acceleration > 0.002 and diff_velocity_trend > 0:
                # 使用二次方程模型：s = v0*t + 0.5*a*t^2
                # 求解 current_diff + v0*t + 0.5*a*t^2 = 0
                v0 = diff_velocity_trend
                a = diff_acceleration
                s0 = current_diff
                
                # 求解二次方程：0.5*a*t^2 + v0*t + s0 = 0
                if a != 0:
                    discriminant = v0**2 - 2*a*s0
                    if discriminant >= 0:
                        t = (-v0 + np.sqrt(discriminant)) / a
                        if t > 0:
                            return max(1, min(10, int(t)))
            
            # 回退到线性预测
            if len(diff_trend) >= 2:
                recent_convergence_speed = np.mean(diff_trend[-2:])
                if recent_convergence_speed > 0:
                    return max(1, min(10, int(abs(current_diff) / recent_convergence_speed)))
            
            return 999
            
        except Exception:
            return 999
    
    def _evaluate_pre_cross_quality_with_acceleration(self, convergence_strength, days_to_cross, momentum_quality, acceleration_strength):
        """
        基于加速度的即将金叉质量评估
        """
        # 爆发性动量 + 高加速度强度 = 高质量
        if momentum_quality == 'explosive' and acceleration_strength >= 85:
            return 'high'
        
        # 强劲动量 + 中高加速度强度 + 短期交叉 = 高质量
        elif momentum_quality == 'strong' and acceleration_strength >= 75 and days_to_cross <= 3:
            return 'high'
        
        # 高收敛强度 + 短期交叉 = 中等质量
        elif convergence_strength >= 80 and days_to_cross <= 5:
            return 'medium'
        
        # 中等动量 + 中等加速度强度 = 中等质量
        elif momentum_quality in ['moderate', 'strong'] and acceleration_strength >= 65:
            return 'medium'
        
        # 其他情况 = 低质量
        else:
            return 'low'
    
    def _validate_crossover_quality(self, macd_line, signal_line, crossover_index):
        """
        验证交叉信号的质量，过滤掉噪音信号
        """
        if crossover_index < 5 or crossover_index >= len(macd_line) - 1:
            return False
        
        # 检查交叉前后的趋势一致性
        pre_trend_days = 3
        post_trend_days = 2
        
        # 获取交叉前后的数据
        pre_macd = macd_line.iloc[crossover_index-pre_trend_days:crossover_index]
        pre_signal = signal_line.iloc[crossover_index-pre_trend_days:crossover_index]
        
        if crossover_index + post_trend_days < len(macd_line):
            post_macd = macd_line.iloc[crossover_index:crossover_index+post_trend_days+1]
            post_signal = signal_line.iloc[crossover_index:crossover_index+post_trend_days+1]
        else:
            post_macd = macd_line.iloc[crossover_index:]
            post_signal = signal_line.iloc[crossover_index:]
        
        # 计算交叉前MACD相对于Signal的趋势
        pre_diff = (pre_macd - pre_signal).values
        if len(pre_diff) > 1:
            pre_trend = np.mean(np.diff(pre_diff))
        else:
            pre_trend = 0
        
        # 计算交叉后MACD相对于Signal的趋势
        post_diff = (post_macd - post_signal).values
        if len(post_diff) > 1:
            post_trend = np.mean(np.diff(post_diff))
        else:
            post_trend = 0
        
        # 金叉验证：交叉前趋势向上，交叉后继续向上
        current_macd = macd_line.iloc[crossover_index]
        current_signal = signal_line.iloc[crossover_index]
        
        if current_macd > current_signal:  # 金叉
            return pre_trend > -0.001 and post_trend > -0.002  # 允许小幅波动
        else:  # 死叉
            return pre_trend < 0.001 and post_trend < 0.002

    def _calculate_line_slope(self, data_series):
        """
        计算数据序列的斜率（趋势方向）
        """
        try:
            if len(data_series) < 2:
                return 0
            
            x = np.arange(len(data_series))
            y = data_series.values
            
            # 使用线性回归计算斜率
            result = linregress(x, y)
            return result.slope
            
        except Exception:
             return 0
    
    def _calculate_diff_dea_acceleration(self, macd_line, signal_line, lookback_days=5):
        """
        计算DIFF（MACD线）和DEA（信号线）的加速度变化
        重点关注DIFF向上势能的加速度放大情况
        
        Parameters:
        - macd_line: MACD线数据
        - signal_line: 信号线数据  
        - lookback_days: 回看天数，默认5天
        
        Returns:
        dict: 包含加速度分析结果
        """
        try:
            if len(macd_line) < lookback_days + 2:
                return {
                    'diff_acceleration': 0,
                    'dea_acceleration': 0,
                    'acceleration_strength': 0,
                    'momentum_quality': 'insufficient_data'
                }
            
            # 获取最近的数据
            recent_macd = macd_line.iloc[-lookback_days:]
            recent_signal = signal_line.iloc[-lookback_days:]
            
            # 计算DIFF的一阶导数（速度）
            diff_velocity = np.diff(recent_macd.values)
            
            # 计算DIFF的二阶导数（加速度）
            if len(diff_velocity) > 1:
                diff_acceleration = np.diff(diff_velocity)
                # 取最近的加速度值
                current_diff_acceleration = diff_acceleration[-1] if len(diff_acceleration) > 0 else 0
                # 计算加速度趋势（加速度是否在增大）
                acceleration_trend = np.mean(diff_acceleration[-2:]) if len(diff_acceleration) >= 2 else current_diff_acceleration
            else:
                current_diff_acceleration = 0
                acceleration_trend = 0
            
            # 计算DEA的加速度（用于对比）
            dea_velocity = np.diff(recent_signal.values)
            if len(dea_velocity) > 1:
                dea_acceleration = np.diff(dea_velocity)
                current_dea_acceleration = dea_acceleration[-1] if len(dea_acceleration) > 0 else 0
            else:
                current_dea_acceleration = 0
            
            # 计算相对加速度（DIFF相对于DEA的加速度优势）
            relative_acceleration = current_diff_acceleration - current_dea_acceleration
            
            # 计算加速度强度评分（0-100分）
            acceleration_strength = self._evaluate_acceleration_strength(
                current_diff_acceleration, 
                acceleration_trend, 
                relative_acceleration,
                recent_macd,
                recent_signal
            )
            
            # 判断动量质量
            momentum_quality = self._classify_momentum_quality(
                acceleration_strength,
                current_diff_acceleration,
                acceleration_trend
            )
            
            return {
                'diff_acceleration': current_diff_acceleration,
                'dea_acceleration': current_dea_acceleration,
                'relative_acceleration': relative_acceleration,
                'acceleration_trend': acceleration_trend,
                'acceleration_strength': acceleration_strength,
                'momentum_quality': momentum_quality,
                'diff_velocity_trend': np.mean(diff_velocity[-2:]) if len(diff_velocity) >= 2 else 0
            }
            
        except Exception as e:
            return {
                'diff_acceleration': 0,
                'dea_acceleration': 0,
                'acceleration_strength': 0,
                'momentum_quality': 'calculation_error'
            }
    
    def _evaluate_acceleration_strength(self, diff_acceleration, acceleration_trend, relative_acceleration, recent_macd, recent_signal):
        """
        评估加速度强度（0-100分）
        重点奖励DIFF向上势能加速度放大的情况
        """
        try:
            base_score = 50
            
            # 1. DIFF加速度评分（权重40%）
            if diff_acceleration > 0.01:  # 强烈向上加速
                diff_score = 95
            elif diff_acceleration > 0.005:  # 中等向上加速
                diff_score = 85
            elif diff_acceleration > 0.002:  # 轻微向上加速
                diff_score = 75
            elif diff_acceleration > 0:  # 微弱向上加速
                diff_score = 65
            elif diff_acceleration > -0.002:  # 接近零加速度
                diff_score = 50
            elif diff_acceleration > -0.005:  # 轻微向下加速
                diff_score = 35
            else:  # 强烈向下加速
                diff_score = 15
            
            # 2. 加速度趋势评分（权重30%）- 加速度是否在放大
            if acceleration_trend > 0.008:  # 加速度快速放大
                trend_score = 100
            elif acceleration_trend > 0.005:  # 加速度中等放大
                trend_score = 90
            elif acceleration_trend > 0.002:  # 加速度轻微放大
                trend_score = 80
            elif acceleration_trend > 0:  # 加速度微弱放大
                trend_score = 70
            elif acceleration_trend > -0.002:  # 加速度稳定
                trend_score = 50
            else:  # 加速度衰减
                trend_score = 30
            
            # 3. 相对加速度评分（权重20%）- DIFF相对DEA的加速度优势
            if relative_acceleration > 0.005:  # DIFF加速度明显超过DEA
                relative_score = 95
            elif relative_acceleration > 0.002:  # DIFF加速度超过DEA
                relative_score = 85
            elif relative_acceleration > 0:  # DIFF加速度略超过DEA
                relative_score = 70
            elif relative_acceleration > -0.002:  # 相对加速度接近
                relative_score = 50
            else:  # DEA加速度超过DIFF
                relative_score = 30
            
            # 4. 位置加权评分（权重10%）- 在零轴附近的加速度更有价值
            current_macd = recent_macd.iloc[-1]
            current_signal = recent_signal.iloc[-1]
            gap = abs(current_macd - current_signal)
            
            if gap < 0.1 and current_macd < current_signal:  # 接近金叉且DIFF在下方
                position_score = 100
            elif gap < 0.2 and current_macd < current_signal:  # 较接近金叉
                position_score = 85
            elif gap < 0.5:  # 中等距离
                position_score = 70
            else:  # 距离较远
                position_score = 50
            
            # 综合评分
            final_score = (
                diff_score * 0.4 +
                trend_score * 0.3 +
                relative_score * 0.2 +
                position_score * 0.1
            )
            
            return min(100, max(0, final_score))
            
        except Exception:
            return 50
    
    def _classify_momentum_quality(self, acceleration_strength, diff_acceleration, acceleration_trend):
        """
        根据加速度强度分类动量质量
        """
        if acceleration_strength >= 85 and diff_acceleration > 0.005 and acceleration_trend > 0.005:
            return 'explosive'  # 爆发性动量
        elif acceleration_strength >= 75 and diff_acceleration > 0.002 and acceleration_trend > 0.002:
            return 'strong'  # 强劲动量
        elif acceleration_strength >= 65 and diff_acceleration > 0:
            return 'moderate'  # 中等动量
        elif acceleration_strength >= 50:
            return 'weak'  # 弱动量
        else:
            return 'declining'  # 衰减动量
    
    def _evaluate_timeliness_quality(self, crossover_index, signal_type):
        """
        原则4：评估信号的时效性质量
        优化版本：重新调整权重，更注重信号的成熟度和持续性
        考虑因素：
        1. 信号的新鲜度（距离当前时间）- 成熟信号更可靠
        2. 信号的持续性（交叉后的表现）- 最重要因素
        3. 信号的强度变化趋势 - 次要因素
        4. 相对历史信号的表现 - 参考因素
        """
        try:
            current_index = len(self.macd_data) - 1
            days_since_signal = current_index - crossover_index
            
            # 1. 新鲜度评分（成熟信号更可靠）
            freshness_score = self._calculate_freshness_score(days_since_signal)
            
            # 2. 持续性评分（交叉后信号是否持续有效）- 提高权重
            persistence_score = self._calculate_persistence_score(crossover_index, signal_type)
            
            # 3. 强度变化评分（信号强度是否在增强）- 降低权重
            strength_trend_score = self._calculate_strength_trend_score(crossover_index)
            
            # 4. 历史表现评分（相对历史信号的表现）- 降低权重
            historical_performance_score = self._calculate_historical_performance_score(crossover_index, signal_type)
            
            # 优化的综合时效性评分：更注重持续性和成熟度
            timeliness_score = (
                freshness_score * 0.25 +        # 降低新鲜度权重
                persistence_score * 0.45 +      # 大幅提高持续性权重
                strength_trend_score * 0.15 +   # 降低强度趋势权重
                historical_performance_score * 0.15  # 降低历史表现权重
            )
            
            return min(100, max(0, timeliness_score))
            
        except Exception as e:
            return 50  # 默认中等分数
    
    def _calculate_freshness_score(self, days_since_signal):
        """
        计算信号新鲜度评分
        优化版本：给成熟信号更高权重，避免过早入场风险
        """
        if days_since_signal <= 1:
            return 60   # 刚形成的信号需要确认，降低权重
        elif days_since_signal <= 3:
            return 85   # 2-3天的信号经过初步确认，较可靠
        elif days_since_signal <= 5:
            return 100  # 3-5天的成熟信号最可靠
        elif days_since_signal <= 7:
            return 90   # 1周内仍然有效
        elif days_since_signal <= 10:
            return 75   # 10天内较有效
        elif days_since_signal <= 14:
            return 50   # 2周内一般
        elif days_since_signal <= 21:
            return 30   # 3周内较弱
        elif days_since_signal <= 30:
            return 15   # 1月内很弱
        else:
            return 5    # 超过1月基本失效
    
    def _calculate_persistence_score(self, crossover_index, signal_type):
        """
        计算信号持续性评分
        """
        try:
            macd_line = self.macd_data['MACD']
            signal_line = self.macd_data['Signal']
            
            # 检查交叉后的表现
            current_index = len(macd_line) - 1
            days_after_cross = current_index - crossover_index
            
            if days_after_cross <= 1:
                return 60  # 刚交叉，给基础分
            
            # 计算交叉后的持续性
            valid_days = 0
            total_days = min(days_after_cross, 10)  # 最多检查10天
            
            for i in range(crossover_index + 1, min(crossover_index + total_days + 1, len(macd_line))):
                if signal_type == 'golden':
                    # 金叉后MACD应该持续在信号线上方
                    if macd_line.iloc[i] > signal_line.iloc[i]:
                        valid_days += 1
                else:  # death cross
                    # 死叉后MACD应该持续在信号线下方
                    if macd_line.iloc[i] < signal_line.iloc[i]:
                        valid_days += 1
            
            # 持续性百分比
            persistence_ratio = valid_days / total_days if total_days > 0 else 0
            
            # 评分标准
            if persistence_ratio >= 0.8:
                return 90
            elif persistence_ratio >= 0.6:
                return 75
            elif persistence_ratio >= 0.4:
                return 55
            else:
                return 30
                
        except Exception:
            return 50
    
    def _calculate_strength_trend_score(self, crossover_index):
        """
        计算信号强度变化趋势评分 - 优化版：重点奖励MACD柱状图向上变化
        """
        try:
            histogram = self.macd_data['Histogram']
            current_index = len(histogram) - 1
            
            # 获取交叉时和当前的柱状图值
            cross_histogram = histogram.iloc[crossover_index]
            current_histogram = histogram.iloc[current_index]
            
            # 计算强度变化
            if crossover_index == current_index:
                return 60  # 刚交叉，给基础分
            
            # 获取交叉后的柱状图趋势
            post_cross_data = histogram.iloc[crossover_index:current_index+1]
            
            if len(post_cross_data) < 2:
                return 60
            
            # 计算趋势斜率
            x = np.arange(len(post_cross_data))
            y = post_cross_data.values
            
            if len(x) > 1:
                slope_result = linregress(x, y)
                slope = slope_result.slope
                
                # 优化评分：更加奖励上升趋势，严惩下降趋势
                if slope > 0.008:    # 极强上升趋势 - 大幅奖励
                    return 95
                elif slope > 0.005:  # 强烈上升趋势 - 高分奖励
                    return 90
                elif slope > 0.003:  # 中强上升趋势 - 中高分
                    return 80
                elif slope > 0.001:  # 中等上升趋势 - 中分
                    return 70
                elif slope > 0:      # 轻微上升趋势 - 基础奖励
                    return 60
                elif slope > -0.001: # 趋势平缓 - 中性
                    return 45
                elif slope > -0.003: # 轻微下降趋势 - 轻微惩罚
                    return 30
                elif slope > -0.005: # 中等下降趋势 - 明显惩罚
                    return 20
                elif slope > -0.008: # 强烈下降趋势 - 严重惩罚
                    return 10
                else:                # 极强下降趋势 - 极严惩罚
                    return 5
            
            return 50
            
        except Exception:
            return 50
    
    def _calculate_historical_performance_score(self, crossover_index, signal_type):
        """
        计算相对历史信号的表现评分
        """
        try:
            macd_line = self.macd_data['MACD']
            signal_line = self.macd_data['Signal']
            
            # 查找历史交叉点
            historical_crosses = []
            
            # 扫描历史数据寻找同类型交叉
            for i in range(1, min(crossover_index, len(macd_line)-1)):
                if signal_type == 'golden':
                    if (macd_line.iloc[i] > signal_line.iloc[i] and 
                        macd_line.iloc[i-1] <= signal_line.iloc[i-1]):
                        historical_crosses.append(i)
                else:  # death cross
                    if (macd_line.iloc[i] < signal_line.iloc[i] and 
                        macd_line.iloc[i-1] >= signal_line.iloc[i-1]):
                        historical_crosses.append(i)
            
            if len(historical_crosses) < 2:
                return 60  # 历史数据不足，给中等分
            
            # 比较当前信号与历史信号的强度
            current_macd_strength = abs(macd_line.iloc[crossover_index])
            historical_strengths = [abs(macd_line.iloc[idx]) for idx in historical_crosses[-3:]]  # 最近3个历史信号
            
            avg_historical_strength = np.mean(historical_strengths)
            
            # 相对强度比较
            if avg_historical_strength == 0:
                return 60
            
            strength_ratio = current_macd_strength / avg_historical_strength
            
            # 评分标准
            if strength_ratio >= 1.5:
                return 85  # 比历史信号强很多
            elif strength_ratio >= 1.2:
                return 75  # 比历史信号强
            elif strength_ratio >= 0.8:
                return 60  # 与历史信号相当
            elif strength_ratio >= 0.5:
                return 45  # 比历史信号弱
            else:
                return 30  # 比历史信号弱很多
            
        except Exception:
            return 60
    
    def _evaluate_death_position_risk(self, macd_line, signal_line, crossover_index):
        """
        评估死叉位置风险（零轴上方死叉风险更高）
        """
        crossover_macd = macd_line.iloc[crossover_index]
        crossover_signal = signal_line.iloc[crossover_index]
        
        if crossover_macd > 0.5:
            # 高位死叉，风险极高
            return 90 + min(10, crossover_macd * 2)
        elif crossover_macd > 0:
            # 零轴上方死叉，风险高
            return 70 + crossover_macd * 40
        elif crossover_macd > -0.3:
            # 零轴附近死叉，风险中等
            return 40 + (crossover_macd + 0.3) * 67
        else:
            # 低位死叉，风险较低
            return max(10, 30 + crossover_macd * 10)
    
    def _evaluate_momentum_risk(self, crossover_index):
        """
        评估动量风险（价格动量和技术指标动量）
        """
        try:
            # 检查价格趋势
            price_data = self.data['Close'].iloc[max(0, crossover_index-10):crossover_index+1]
            if len(price_data) > 2:
                price_slope = (price_data.iloc[-1] - price_data.iloc[0]) / len(price_data)
                if price_slope < -0.5:  # 价格快速下跌
                    price_risk = 80
                elif price_slope < -0.1:
                    price_risk = 60
                elif price_slope < 0:
                    price_risk = 40
                else:
                    price_risk = 20
            else:
                price_risk = 50
            
            # 检查MACD柱状图趋势
            histogram = self.macd_data['Histogram'].iloc[max(0, crossover_index-5):crossover_index+1]
            if len(histogram) > 2:
                hist_slope = (histogram.iloc[-1] - histogram.iloc[0]) / len(histogram)
                if hist_slope < -0.02:  # MACD动量急速衰减
                    macd_risk = 80
                elif hist_slope < -0.01:
                    macd_risk = 60
                elif hist_slope < 0:
                    macd_risk = 40
                else:
                    macd_risk = 20
            else:
                macd_risk = 50
            
            return (price_risk * 0.6 + macd_risk * 0.4)
            
        except Exception:
            return 50
    
    def _evaluate_death_volume_risk(self, crossover_index):
        """
        评估死叉时的量能风险（放量下跑风险高）
        """
        if 'Volume' not in self.data.columns:
            return 50
        
        try:
            volume_data = self.data['Volume']
            crossover_volume = volume_data.iloc[crossover_index]
            
            # 计算前期平均成交量
            if crossover_index >= 10:
                avg_volume = volume_data.iloc[crossover_index-10:crossover_index].mean()
            else:
                avg_volume = volume_data.iloc[:crossover_index].mean()
            
            if avg_volume == 0:
                return 50
            
            # 计算放量倍数
            volume_ratio = crossover_volume / avg_volume
            
            # 死叉时放量越大风险越高
            if volume_ratio >= 3.0:
                return 90  # 巨量死叉，风险极高
            elif volume_ratio >= 2.0:
                return 75  # 放量死叉，风险高
            elif volume_ratio >= 1.5:
                return 60  # 中等放量，风险中等
            elif volume_ratio >= 1.0:
                return 40  # 正常量能，风险较低
            else:
                return 25  # 缩量死叉，风险较低
                
        except Exception:
            return 50
    
    def _evaluate_position_quality(self, macd_line, signal_line, crossover_index):
        """
        原则1：评估金叉位置质量（零轴上方或附近）
        优化版：增加DIFF向上势能加速度因子权重
        """
        crossover_macd = macd_line.iloc[crossover_index]
        crossover_signal = signal_line.iloc[crossover_index]
        
        # 基础位置评分
        base_score = self._calculate_base_position_score(crossover_macd)
        
        # 新增：加速度因子评分（权重30%）
        acceleration_score = self._calculate_position_acceleration_score(
            macd_line, signal_line, crossover_index
        )
        
        # 趋势确认评分（权重20%）
        trend_score = self._calculate_position_trend_score(
            macd_line, signal_line, crossover_index
        )
        
        # 综合评分：基础位置50% + 加速度因子30% + 趋势确认20%
        final_score = (
            base_score * 0.5 +
            acceleration_score * 0.3 +
            trend_score * 0.2
        )
        
        return min(100, max(0, final_score))
    
    def _calculate_base_position_score(self, crossover_macd):
        """
        计算基础位置评分
        """
        # 评分标准：
        # 90-100分：金叉发生在零轴上方
        # 70-89分：金叉发生在零轴附近（-0.5到0之间）
        # 50-69分：金叉发生在零轴下方但MACD趋势向上
        # 0-49分：金叉发生在零轴下方且趋势不明
        
        if crossover_macd > 0:
            # 零轴上方，优秀位置
            score = 90 + min(10, crossover_macd * 5)  # 越高越好，最高100分
        elif crossover_macd > -0.5:
            # 零轴附近，良好位置
            score = 70 + (crossover_macd + 0.5) * 38  # -0.5到0之间映射到70-89分
        else:
            # 零轴下方，需要检查趋势
            score = max(0, 30 + crossover_macd * 10)
        
        return score
    
    def _calculate_position_acceleration_score(self, macd_line, signal_line, crossover_index):
        """
        计算位置相关的加速度评分（新增）
        重点评估金叉时刻DIFF的向上势能加速度
        """
        try:
            # 确保有足够的数据计算加速度
            if crossover_index < 5:
                return 50  # 数据不足，给中等分
            
            # 获取金叉前后的数据用于加速度计算
            start_idx = max(0, crossover_index - 4)
            end_idx = min(len(macd_line), crossover_index + 2)
            
            analysis_macd = macd_line.iloc[start_idx:end_idx]
            analysis_signal = signal_line.iloc[start_idx:end_idx]
            
            # 计算加速度分析
            acceleration_analysis = self._calculate_diff_dea_acceleration(
                analysis_macd, analysis_signal, lookback_days=min(5, len(analysis_macd))
            )
            
            acceleration_strength = acceleration_analysis['acceleration_strength']
            momentum_quality = acceleration_analysis['momentum_quality']
            diff_acceleration = acceleration_analysis['diff_acceleration']
            acceleration_trend = acceleration_analysis['acceleration_trend']
            
            # 基于加速度特征的评分
            score = 50  # 基础分
            
            # 1. 加速度强度奖励（40%权重）
            if acceleration_strength >= 90:
                score += 40  # 极强加速度
            elif acceleration_strength >= 80:
                score += 35  # 强加速度
            elif acceleration_strength >= 70:
                score += 30  # 中等加速度
            elif acceleration_strength >= 60:
                score += 20  # 轻微加速度
            elif acceleration_strength >= 50:
                score += 10  # 微弱加速度
            
            # 2. 动量质量奖励（30%权重）
            momentum_bonus = {
                'explosive': 30,  # 爆发性动量
                'strong': 25,     # 强劲动量
                'moderate': 15,   # 中等动量
                'weak': 8,        # 弱动量
                'declining': 0    # 衰减动量
            }
            score += momentum_bonus.get(momentum_quality, 0)
            
            # 3. DIFF加速度直接奖励（20%权重）
            if diff_acceleration > 0.01:
                score += 20  # 极强向上加速
            elif diff_acceleration > 0.005:
                score += 16  # 强向上加速
            elif diff_acceleration > 0.002:
                score += 12  # 中等向上加速
            elif diff_acceleration > 0:
                score += 8   # 轻微向上加速
            
            # 4. 加速度趋势奖励（10%权重）
            if acceleration_trend > 0.008:
                score += 10  # 加速度快速放大
            elif acceleration_trend > 0.005:
                score += 8   # 加速度中等放大
            elif acceleration_trend > 0.002:
                score += 6   # 加速度轻微放大
            elif acceleration_trend > 0:
                score += 4   # 加速度微弱放大
            
            return min(100, max(0, score))
            
        except Exception as e:
            return 50  # 计算出错时返回中等分
    
    def _calculate_position_trend_score(self, macd_line, signal_line, crossover_index):
        """
        计算位置相关的趋势确认评分
        """
        try:
            if crossover_index < 5:
                return 50
            
            # 检查金叉前的MACD趋势
            recent_macd = macd_line.iloc[max(0, crossover_index-5):crossover_index+1]
            if len(recent_macd) > 2:
                slope = (recent_macd.iloc[-1] - recent_macd.iloc[0]) / len(recent_macd)
                if slope > 0:
                    # 上升趋势
                    return min(100, 50 + slope * 100)
                else:
                    # 下降或平缓趋势
                    return max(0, 30 + slope * 50)
            else:
                return 50
                
        except Exception:
            return 50
    
    def _evaluate_resonance_quality(self, crossover_index):
        """
        原则2：评估共振确认质量（底背离或突破阻力位）
        增强版：集成改进的背离检测算法
        """
        if crossover_index < 10:
            return 40
        
        try:
            # 使用改进的背离检测
            divergence_score = self._check_bullish_divergence(crossover_index)
            
            # 额外的背离强度分析（如果有足够数据）
            if self.macd_data is not None and crossover_index >= 20:
                lookback_days = min(60, crossover_index)
                end_idx = crossover_index + 1
                start_idx = end_idx - lookback_days
                
                price_data = self.data['Close'].iloc[start_idx:end_idx]
                macd_data = self.macd_data['MACD'].iloc[start_idx:end_idx]
                histogram_data = self.macd_data['Histogram'].iloc[start_idx:end_idx]
                
                # 获取完整的背离分析结果
                divergence_result = self.divergence_detector.detect_divergences(
                    price_data, macd_data, histogram_data
                )
                
                # 根据背离强度和方向调整共振质量
                divergence_strength = divergence_result['divergence_strength']
                
                # 如果有显著的看涨背离，提升共振质量
                if divergence_result['has_significant_divergence'] and divergence_strength['direction'] == 'bullish':
                    divergence_score = min(100, divergence_score + divergence_strength['confidence'] * 20)
                
                # 如果有看跌背离，降低共振质量
                elif divergence_strength['direction'] == 'bearish':
                    divergence_score = max(20, divergence_score - divergence_strength['confidence'] * 15)
            
            # 检查价格突破
            breakthrough_score = self._check_price_breakthrough(crossover_index)
            
            # 检查均线支撑
            ma_support_score = self._check_ma_support(crossover_index)
            
            # 综合评分（调整权重以突出背离分析的重要性）
            total_score = (
                divergence_score * 0.5 +      # 背离分析权重保持50%
                breakthrough_score * 0.3 +     # 价格突破30%
                ma_support_score * 0.2         # MA支撑20%
            )
            
            return min(100, max(0, int(total_score)))
        
        except Exception:
            return 50
    
    def _check_bullish_divergence(self, crossover_index):
        """
        使用改进的背离检测器检查MACD底背离
        """
        if crossover_index < 20 or self.macd_data is None:
            return 30
        
        try:
            # 获取足够的历史数据进行背离分析
            lookback_days = min(60, crossover_index)
            end_idx = crossover_index + 1
            start_idx = end_idx - lookback_days
            
            # 提取价格和MACD数据
            price_data = self.data['Close'].iloc[start_idx:end_idx]
            macd_data = self.macd_data['MACD'].iloc[start_idx:end_idx]
            histogram_data = self.macd_data['Histogram'].iloc[start_idx:end_idx]
            
            # 使用背离检测器进行分析
            divergence_result = self.divergence_detector.detect_divergences(
                price_data, macd_data, histogram_data
            )
            
            # 计算背离评分
            bullish_div = divergence_result['bullish_divergences']
            divergence_strength = divergence_result['divergence_strength']
            
            base_score = 30
            
            # 根据检测到的背离类型和强度计算分数
            if bullish_div['any_detected']:
                # 经典看涨背离权重最高
                if bullish_div['classic']['detected']:
                    base_score += bullish_div['classic']['strength'] * 40
                
                # 隐性看涨背离
                if bullish_div['hidden']['detected']:
                    base_score += bullish_div['hidden']['strength'] * 25
                
                # 柱状图背离
                if bullish_div['histogram']['detected']:
                    base_score += bullish_div['histogram']['strength'] * 25
                
                # 根据整体背离强度和可靠性调整
                reliability_bonus = 0
                if divergence_strength['reliability'] == 'high':
                    reliability_bonus = 10
                elif divergence_strength['reliability'] == 'medium':
                    reliability_bonus = 5
                
                base_score += reliability_bonus
            else:
                # 无明显背离，但根据整体背离倾向给予基础分
                if divergence_strength['direction'] == 'bullish':
                    base_score += divergence_strength['bullish_score'] * 20
            
            return min(100, int(base_score))
        
        except Exception as e:
            # 发生错误时返回默认分数
            return 30
    
    def _check_price_breakthrough(self, crossover_index):
        """
        检查价格是否突破关键阻力位
        """
        if crossover_index < 10:
            return 30
        
        try:
            # 获取金叉前后的价格数据
            recent_prices = self.data['Close'].iloc[crossover_index-10:crossover_index+3]
            crossover_price = self.data['Close'].iloc[crossover_index]
            
            # 计算前期阻力位（前10天的最高价）
            resistance_level = recent_prices.iloc[:-3].max()
            
            # 检查突破强度
            if crossover_price > resistance_level:
                breakthrough_strength = (crossover_price - resistance_level) / resistance_level
                return min(100, 70 + breakthrough_strength * 200)
            elif crossover_price > resistance_level * 0.98:  # 接近突破
                return 60
            else:
                return 30
        
        except Exception:
            return 30
    
    def _check_ma_support(self, crossover_index):
        """
        检查均线支撑
        """
        if crossover_index < 20:
            return 30
        
        try:
            # 计算20日均线
            ma20 = self.data['Close'].rolling(window=20).mean()
            crossover_price = self.data['Close'].iloc[crossover_index]
            ma20_value = ma20.iloc[crossover_index]
            
            # 检查价格相对于均线的位置
            if crossover_price > ma20_value:
                return 80  # 在均线上方，支撑强
            elif crossover_price > ma20_value * 0.98:
                return 60  # 接近均线
            else:
                return 30  # 在均线下方
        
        except Exception:
            return 30
    
    def _evaluate_volume_quality(self, crossover_index):
        """
        原则3：评估量能驱动质量（成交量明显放大）
        """
        if 'Volume' not in self.data.columns:
            return 50  # 无成交量数据时给中等分
        
        try:
            # 获取成交量数据
            volume_data = self.data['Volume']
            crossover_volume = volume_data.iloc[crossover_index]
            
            # 计算前期平均成交量（前10天）
            if crossover_index >= 10:
                avg_volume = volume_data.iloc[crossover_index-10:crossover_index].mean()
            else:
                avg_volume = volume_data.iloc[:crossover_index].mean()
            
            if avg_volume == 0:
                return 50
            
            # 计算放量倍数
            volume_ratio = crossover_volume / avg_volume
            
            # 评分标准：
            # 90-100分：放量2倍以上
            # 70-89分：放量1.5-2倍
            # 50-69分：放量1.2-1.5倍
            # 30-49分：放量1.0-1.2倍
            # 0-29分：缩量
            
            if volume_ratio >= 2.0:
                return min(100, 90 + (volume_ratio - 2) * 5)
            elif volume_ratio >= 1.5:
                return 70 + (volume_ratio - 1.5) * 38
            elif volume_ratio >= 1.2:
                return 50 + (volume_ratio - 1.2) * 67
            elif volume_ratio >= 1.0:
                return 30 + (volume_ratio - 1.0) * 100
            else:
                return max(0, volume_ratio * 30)
        
        except Exception:
            return 50
    
    def calculate_rsi(self, window=14):
        """
        计算RSI指标
        :param window: RSI计算窗口，默认14
        """
        if self.data is None:
            print("请先获取股票数据")
            return False
        
        # 计算价格变化
        delta = self.data['Close'].diff()
        delta = delta[1:]  # 删除第一天的NaN值
        
        # 分离上涨和下跌
        up = delta.copy()
        down = delta.copy()
        up[up < 0] = 0
        down[down > 0] = 0
        
        # 计算平均上涨和下跌
        avg_gain = up.rolling(window=window).mean()
        avg_loss = abs(down.rolling(window=window).mean())
        
        # 计算RS
        rs = avg_gain / avg_loss
        
        # 计算RSI
        rsi = 100 - (100 / (1 + rs))
        
        self.rsi_data = rsi
        return True
    
    def get_rsi_status(self):
        """
        获取RSI状态并给出分析
        """
        if self.rsi_data is None:
            print("请先计算RSI指标")
            return None
        
        current_rsi = self.rsi_data.iloc[-1]
        
        if current_rsi > 70:
            status = "超买"
            advice = "RSI高于70，股票可能处于超买状态，建议谨慎买入或考虑卖出"
        elif current_rsi < 30:
            status = "超卖"
            advice = "RSI低于30，股票可能处于超卖状态，可能是买入机会"
        else:
            status = "中性"
            advice = "RSI处于30-70之间，市场趋势中性"
        
        return {
            'value': current_rsi,
            'status': status,
            'advice': advice
        }
    
    def get_enhanced_investment_analysis(self):
        """
        基于优化算法的智能投资分析，提供胜率预测、持仓比例和持有时间建议
        """
        # 获取MACD交叉信息
        macd_info = self.detect_macd_crossover()
        # 获取RSI信息
        rsi_info = self.get_rsi_status()
        # 获取增强分析
        enhanced_analysis = self.calculate_enhanced_metrics()
        
        if not macd_info or not rsi_info:
            return None
        
        # 计算综合投资评分
        investment_score = self.calculate_investment_score(macd_info, rsi_info, enhanced_analysis)
        
        # 生成投资建议
        investment_advice = self.generate_investment_advice(investment_score, macd_info, rsi_info, enhanced_analysis)
        
        return investment_advice
    
    def get_investment_suggestion(self):
        """
        根据高胜率MACD金叉四大核心原则、死叉风险评估和RSI给出投资建议
        """
        # 获取MACD交叉信息
        macd_info = self.detect_macd_crossover()
        # 获取RSI信息
        rsi_info = self.get_rsi_status()
        
        if not macd_info or not rsi_info:
            return "无法获取足够的数据进行分析"
        
        suggestion = f"股票代码: {self.symbol}\n"
        suggestion += "="*50 + "\n"
        suggestion += "📊 高胜率MACD金叉分析系统\n"
        suggestion += "="*50 + "\n"
        
        # MACD分析
        suggestion += "\n📈 MACD技术分析:\n"
        suggestion += "-"*30 + "\n"
        
        # 金叉分析
        if macd_info['golden_cross']['detected']:
            suggestion += f"  ✅ 金叉日期: {macd_info['golden_cross']['date'].strftime('%Y-%m-%d')}\n"
            suggestion += f"  🏆 金叉质量: {macd_info['golden_cross']['quality'].upper()} (评分: {macd_info['golden_cross']['quality_score']:.1f}/100)\n"
            suggestion += f"  🎯 位置评分: {macd_info['golden_cross']['position_score']:.1f}/100\n"
            suggestion += f"  🌊 共振评分: {macd_info['golden_cross']['resonance_score']:.1f}/100\n"
            suggestion += f"  📊 量能评分: {macd_info['golden_cross']['volume_score']:.1f}/100\n"
            suggestion += f"  ⏰ 时效评分: {macd_info['golden_cross']['timeliness_score']:.1f}/100\n"
            
            # 质量详细解释
            if macd_info['golden_cross']['quality'] == 'high':
                suggestion += "  ✨ 高质量金叉: 同时满足位置、共振、量能、时效四大核心原则\n"
            elif macd_info['golden_cross']['quality'] == 'medium':
                suggestion += "  ⚠️ 中等质量金叉: 部分满足核心原则，需谨慎\n"
            else:
                suggestion += "  ⛔ 低质量金叉: 不满足高胜率条件，风险较高\n"
        else:
            suggestion += "  ❌ 最近未发现金叉信号\n"
        
        # 死叉分析
        if macd_info['death_cross']['detected']:
            suggestion += f"  ⚠️ 死叉日期: {macd_info['death_cross']['date'].strftime('%Y-%m-%d')}\n"
            suggestion += f"  🚨 风险等级: {macd_info['death_cross']['risk_level'].upper()} (评分: {macd_info['death_cross']['risk_score']:.1f}/100)\n"
            suggestion += f"  📍 位置风险: {macd_info['death_cross']['position_risk']:.1f}/100\n"
            suggestion += f"  📉 动量风险: {macd_info['death_cross']['momentum_risk']:.1f}/100\n"
            suggestion += f"  📊 量能风险: {macd_info['death_cross']['volume_risk']:.1f}/100\n"
            suggestion += f"  ⏰ 时效风险: {macd_info['death_cross']['timeliness_risk']:.1f}/100\n"
            
            # 风险详细解释
            if macd_info['death_cross']['risk_level'] == 'high':
                suggestion += "  🚨 高风险死叉: 建议立即减仓或止损\n"
            elif macd_info['death_cross']['risk_level'] == 'medium':
                suggestion += "  ⚠️ 中等风险死叉: 建议谨慎清仓，控制仓位\n"
            else:
                suggestion += "  🟡 低风险死叉: 可适度减仓，注意观察\n"
        
        suggestion += f"  📉 当前MACD值: {macd_info['current_macd']:.4f}\n"
        suggestion += f"  📈 当前信号线: {macd_info['current_signal']:.4f}\n"
        suggestion += f"  📋 MACD柱状图: {macd_info['current_histogram']:.4f}\n"
        
        # RSI分析
        suggestion += "\n🌡️ RSI动量分析:\n"
        suggestion += "-"*30 + "\n"
        suggestion += f"  📊 当前RSI值: {rsi_info['value']:.2f}\n"
        suggestion += f"  🏷️ 市场状态: {rsi_info['status']}\n"
        suggestion += f"  📝 RSI建议: {rsi_info['advice']}\n"
        
        # 综合投资建议
        suggestion += "\n YYS 智能投资建议:\n"
        suggestion += "="*30 + "\n"
        
        # 考虑死叉风险
        if macd_info['death_cross']['detected'] and macd_info['death_cross']['risk_level'] == 'high':
            suggestion += "  🚨 强烈建议卖出\n"
            suggestion += "     • 检测到高风险死叉信号\n"
            suggestion += "     • 建议立即清仓或设置止损\n"
        elif macd_info['death_cross']['detected'] and macd_info['death_cross']['risk_level'] == 'medium':
            suggestion += "  📉 建议减仓\n"
            suggestion += "     • 检测到中等风险死叉信号\n"
            suggestion += "     • 建议逐步减仓，控制风险\n"
        elif macd_info['golden_cross']['detected']:
            if macd_info['golden_cross']['quality'] == 'high':
                if rsi_info['status'] != "超买":
                    suggestion += "  🚀 强烈推荐买入\n"
                    suggestion += "     • 高质量MACD金叉 + RSI未超买\n"
                    suggestion += "     • 满足四大核心原则，胜率较高\n"
                    suggestion += "     • 建议仓位: 70-80%\n"
                else:
                    suggestion += "  ⚠️ 谨慎买入\n"
                    suggestion += "     • 高质量MACD金叉但RSI超买\n"
                    suggestion += "     • 建议等待RSI回调后介入\n"
                    suggestion += "     • 建议仓位: 30-40%\n"
            elif macd_info['golden_cross']['quality'] == 'medium':
                if rsi_info['status'] == "超卖":
                    suggestion += "  📈 适度买入\n"
                    suggestion += "     • 中等质量MACD金叉 + RSI超卖\n"
                    suggestion += "     • 可分批介入，控制风险\n"
                    suggestion += "     • 建议仓位: 40-50%\n"
                elif rsi_info['status'] != "超买":
                    suggestion += "  🔄 谨慎参与\n"
                    suggestion += "     • 中等质量MACD金叉\n"
                    suggestion += "     • 建议等待更强信号确认\n"
                    suggestion += "     • 建议仓位: 20-30%\n"
                else:
                    suggestion += "  🚫 建议观望\n"
                    suggestion += "     • 中等质量金叉但RSI超买\n"
                    suggestion += "     • 等待更好的介入机会\n"
            else:  # low quality
                suggestion += "  ⛔ 不建议买入\n"
                suggestion += "     • 低质量金叉，不满足高胜率条件\n"
                suggestion += "     • 可能为假信号，风险较高\n"
                suggestion += "     • 建议继续观望\n"
        else:
            if rsi_info['status'] == "超卖":
                suggestion += "  🔍 考虑分批买入\n"
                suggestion += "     • 无MACD金叉但RSI超卖\n"
                suggestion += "     • 可能存在反弹机会\n"
                suggestion += "     • 建议仓位: 10-20%\n"
            elif rsi_info['status'] == "超买":
                suggestion += "  📉 建议卖出或减仓\n"
                suggestion += "     • 无MACD金叉且RSI超买\n"
                suggestion += "     • 上涨动能不足，回调风险高\n"
            else:
                suggestion += "  🔄 建议观望\n"
                suggestion += "     • 市场趋势不明朗\n"
                suggestion += "     • 等待明确信号出现\n"
        
        # 风险提示
        suggestion += "\n⚠️ 风险提示:\n"
        suggestion += "-"*20 + "\n"
        suggestion += "  • 股市有风险，投资需谨慎\n"
        suggestion += "  • 建议结合其他技术指标综合判断\n"
        suggestion += "  • 注意仓位管理和止损设置\n"
        suggestion += "  • 本分析仅供参考，不构成投资建议\n"
        
        return suggestion
        
    def calculate_enhanced_metrics(self):
        """
        计算增强指标：包括市场情绪、趋势强度、波动率、价格估值等
        """
        try:
            # 1. 计算趋势强度 (ADX-like)
            trend_strength = self._calculate_trend_strength()
            
            # 2. 计算波动率
            volatility = self._calculate_volatility()
            
            # 3. 计算价格动量
            price_momentum = self._calculate_price_momentum()
            
            # 4. 计算支撑位和阻力位
            support_resistance = self._calculate_support_resistance()
            
            # 5. 计算市场环境评分
            market_environment = self._calculate_market_environment()
            
            # 6. 新增：计算价格估值评分（重点奖励低位价格）
            valuation_score = self._calculate_valuation_score()
            
            return {
                'trend_strength': trend_strength,
                'volatility': volatility,
                'price_momentum': price_momentum,
                'support_resistance': support_resistance,
                'market_environment': market_environment,
                'valuation_score': valuation_score  # 新增价格估值评分
            }
        except Exception as e:
            print(f"计算增强指标时出错: {e}")
            return {
                'trend_strength': 50,
                'volatility': 50,
                'price_momentum': 50,
                'support_resistance': 50,
                'market_environment': 50,
                'valuation_score': 50
            }
    
    def _calculate_trend_strength(self):
        """
        计算趋势强度（类似ADX指标）
        """
        try:
            close_prices = self.data['Close']
            high_prices = self.data['High']
            low_prices = self.data['Low']
            
            # 计算真实波动幅度(TR)
            tr1 = high_prices - low_prices
            tr2 = abs(high_prices - close_prices.shift(1))
            tr3 = abs(low_prices - close_prices.shift(1))
            true_range = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
            
            # 计算方向运动(DM)
            dm_plus = high_prices.diff()
            dm_minus = low_prices.diff() * -1
            
            # 只保留正值
            dm_plus[dm_plus < 0] = 0
            dm_minus[dm_minus < 0] = 0
            
            # 计算14期平均
            atr = true_range.rolling(window=14).mean()
            di_plus = (dm_plus.rolling(window=14).mean() / atr) * 100
            di_minus = (dm_minus.rolling(window=14).mean() / atr) * 100
            
            # 计算DX
            dx = abs(di_plus - di_minus) / (di_plus + di_minus) * 100
            dx = dx.fillna(0)
            
            # ADX是 DX 的14期平均
            adx = dx.rolling(window=14).mean()
            
            current_adx = adx.iloc[-1] if not adx.empty else 25
            
            # 转换为0-100评分
            if current_adx >= 50:
                return 95  # 极强趋势
            elif current_adx >= 40:
                return 85  # 强趋势
            elif current_adx >= 30:
                return 70  # 中等趋势
            elif current_adx >= 20:
                return 50  # 弱趋势
            else:
                return 30  # 无趋势
                
        except Exception:
            return 50
    
    def _calculate_volatility(self):
        """
        计算波动率评分（低波动性对金叉信号更有利）
        """
        try:
            close_prices = self.data['Close']
            returns = close_prices.pct_change().dropna()
            
            # 计算20日波动率
            volatility = returns.rolling(window=20).std() * np.sqrt(252)  # 年化波动率
            current_vol = volatility.iloc[-1] if not volatility.empty else 0.2
            
            # 波动率评分：低波动更好
            if current_vol <= 0.15:  # 15%以下
                return 90  # 低波动，好
            elif current_vol <= 0.25:  # 25%以下
                return 70
            elif current_vol <= 0.35:  # 35%以下
                return 50
            elif current_vol <= 0.50:  # 50%以下
                return 30
            else:
                return 15  # 高波动，危险
                
        except Exception:
            return 50
    
    def _calculate_price_momentum(self):
        """
        计算价格动量评分
        """
        try:
            close_prices = self.data['Close']
            
            # 计算多期动量
            momentum_5 = (close_prices.iloc[-1] / close_prices.iloc[-6] - 1) * 100  # 5日动量
            momentum_10 = (close_prices.iloc[-1] / close_prices.iloc[-11] - 1) * 100  # 10日动量
            momentum_20 = (close_prices.iloc[-1] / close_prices.iloc[-21] - 1) * 100  # 20日动量
            
            # 综合动量评分（正动量更好）
            avg_momentum = (momentum_5 * 0.5 + momentum_10 * 0.3 + momentum_20 * 0.2)
            
            if avg_momentum >= 10:
                return 95  # 强劲上涨
            elif avg_momentum >= 5:
                return 80
            elif avg_momentum >= 2:
                return 65
            elif avg_momentum >= 0:
                return 50
            elif avg_momentum >= -3:
                return 35
            elif avg_momentum >= -8:
                return 20
            else:
                return 10  # 强劲下跌
                
        except Exception:
            return 50
    
    def _calculate_support_resistance(self):
        """
        计算支撑位和阻力位评分
        """
        try:
            close_prices = self.data['Close']
            high_prices = self.data['High']
            low_prices = self.data['Low']
            
            current_price = close_prices.iloc[-1]
            
            # 计算近20日的支撑位和阻力位
            recent_data = self.data.tail(20)
            support_level = recent_data['Low'].min()
            resistance_level = recent_data['High'].max()
            
            # 计算当前价格在支撑阻力区间的位置
            price_range = resistance_level - support_level
            if price_range == 0:
                return 50
            
            position_ratio = (current_price - support_level) / price_range
            
            # 接近支撑位是好的买入机会
            if position_ratio <= 0.2:  # 接近支撑位
                return 85
            elif position_ratio <= 0.4:
                return 70
            elif position_ratio <= 0.6:
                return 50
            elif position_ratio <= 0.8:
                return 35
            else:  # 接近阻力位
                return 20
                
        except Exception:
            return 50
    
    def _calculate_market_environment(self):
        """
        计算市场环境评分（通过市场广度等指标）
        """
        try:
            close_prices = self.data['Close']
            
            # 计算市场趋势（使用多期均线）
            ma5 = close_prices.rolling(window=5).mean()
            ma10 = close_prices.rolling(window=10).mean()
            ma20 = close_prices.rolling(window=20).mean()
            
            current_price = close_prices.iloc[-1]
            current_ma5 = ma5.iloc[-1]
            current_ma10 = ma10.iloc[-1]
            current_ma20 = ma20.iloc[-1]
            
            # 多头排列评分
            if current_price > current_ma5 > current_ma10 > current_ma20:
                return 90  # 完美多头排列
            elif current_price > current_ma5 > current_ma10:
                return 75
            elif current_price > current_ma5:
                return 60
            elif current_price > current_ma20:
                return 45
            else:
                return 25  # 空头排列
                
        except Exception:
            return 50
    
    def calculate_investment_score(self, macd_info, rsi_info, enhanced_analysis):
        """
        计算综合投资评分（优化版 - 增强即将金叉和低估值低RSI的评分）
        """
        base_score = 0
        risk_factor = 1.0
        rsi_penalty_factor = 1.0  # RSI惩罚系数
        pre_golden_bonus = 0  # 即将金叉奖励
        
        # 1. MACD信号评分（权重25%）
        if macd_info['golden_cross']['detected']:
            # 金叉质量评分
            macd_score = macd_info['golden_cross']['quality_score']
            
            # 时效性加权
            timeliness_bonus = macd_info['golden_cross']['timeliness_score'] / 100 * 0.2
            macd_score = macd_score * (1 + timeliness_bonus)
            
        elif macd_info['death_cross']['detected']:
            # 死叉惩罚
            death_penalty = macd_info['death_cross']['risk_score'] / 100
            macd_score = -(50 * death_penalty)  # 负分
            risk_factor *= 1.5  # 增加风险系数
        else:
            macd_score = 30  # 无明确信号
        
        # 新增：即将金叉的奖励评分（优化版 - 重点关注加速度）
        if 'pre_golden_cross' in macd_info and macd_info['pre_golden_cross']['detected']:
            pre_cross_info = macd_info['pre_golden_cross']
            
            # 获取加速度相关信息
            momentum_quality = pre_cross_info.get('momentum_quality', 'weak')
            diff_acceleration = pre_cross_info.get('diff_acceleration', 0)
            acceleration_trend = pre_cross_info.get('acceleration_trend', 0)
            acceleration_bonus = pre_cross_info.get('acceleration_bonus', 0)
            
            # 基础奖励（根据收敛质量）
            if pre_cross_info['quality'] == 'high':
                base_pre_golden_bonus = 25  # 高质量即将金叉
            elif pre_cross_info['quality'] == 'medium':
                base_pre_golden_bonus = 15  # 中等质量
            else:
                base_pre_golden_bonus = 8   # 低质量
            
            # 新增：基于DIFF向上势能加速度的大幅奖励
            acceleration_multiplier = 1.0
            
            # 1. 动量质量加速度奖励（用户重点关注）
            if momentum_quality == 'explosive':
                acceleration_multiplier *= 2.5  # 爆发性动量，2.5倍奖励
            elif momentum_quality == 'strong':
                acceleration_multiplier *= 2.0  # 强劲动量，2倍奖励
            elif momentum_quality == 'moderate':
                acceleration_multiplier *= 1.5  # 中等动量，1.5倍奖励
            elif momentum_quality == 'weak':
                acceleration_multiplier *= 1.2  # 弱动量，1.2倍奖励
            
            # 2. DIFF加速度直接奖励（用户特别要求）
            if diff_acceleration > 0.01:
                acceleration_multiplier *= 2.2  # 极强向上加速，2.2倍奖励
            elif diff_acceleration > 0.005:
                acceleration_multiplier *= 1.8  # 强向上加速，1.8倍奖励
            elif diff_acceleration > 0.002:
                acceleration_multiplier *= 1.5  # 中等向上加速，1.5倍奖励
            elif diff_acceleration > 0:
                acceleration_multiplier *= 1.3  # 轻微向上加速，1.3倍奖励
            
            # 3. 加速度趋势奖励（加速度是否在放大）
            if acceleration_trend > 0.008:
                acceleration_multiplier *= 1.8  # 加速度快速放大，1.8倍奖励
            elif acceleration_trend > 0.005:
                acceleration_multiplier *= 1.6  # 加速度中等放大，1.6倍奖励
            elif acceleration_trend > 0.002:
                acceleration_multiplier *= 1.4  # 加速度轻微放大，1.4倍奖励
            elif acceleration_trend > 0:
                acceleration_multiplier *= 1.2  # 加速度微弱放大，1.2倍奖励
            
            # 4. 加速度奖励分数直接加成
            acceleration_direct_bonus = acceleration_bonus * 0.8  # 80%的加速度奖励分数
            
            # 计算最终的即将金叉奖励
            pre_golden_bonus = (base_pre_golden_bonus * acceleration_multiplier) + acceleration_direct_bonus
            
            # 根据预估交叉时间调整奖励（保留原有逻辑）
            days_to_cross = pre_cross_info.get('days_to_cross', 999)
            if days_to_cross <= 2:
                pre_golden_bonus *= 1.3  # 2天内可能金叉，额外30%奖励
            elif days_to_cross <= 5:
                pre_golden_bonus *= 1.1  # 5天内可能金叉，额外10%奖励
            
            # 设置奖励上限（防止过度奖励）
            pre_golden_bonus = min(80, pre_golden_bonus)
            
            # 如果没有实际金叉，但有即将金叉，替换MACD评分
            if not macd_info['golden_cross']['detected']:
                # 对于高加速度的即将金叉，给予更高的基础分
                if acceleration_multiplier >= 2.0:
                    macd_score = max(macd_score, 60 + pre_golden_bonus)  # 高加速度基础分提高到60
                elif acceleration_multiplier >= 1.5:
                    macd_score = max(macd_score, 50 + pre_golden_bonus)  # 中等加速度基础分50
                else:
                    macd_score = max(macd_score, 40 + pre_golden_bonus)  # 低加速度基础分40
        
        base_score += macd_score * 0.25  # 权重25%
        
        # 2. RSI评分（权重20%）- 大幅优化低RSI奖励
        rsi_value = rsi_info['value']
        
        # 优化RSI评分：特别奖励低于30的RSI值，这是用户特别要求的
        if rsi_value < 15:  # 极度超卖 - 最高奖励但考虑极端风险
            rsi_score = 92
            rsi_penalty_factor = 1.0
        elif rsi_value < 20:  # 严重超卖 - 高奖励（用户重点关注）
            rsi_score = 95
            rsi_penalty_factor = 0.95  # 轻微降低风险系数，因为反弹概率高
        elif rsi_value < 25:  # 明显超卖 - 中高奖励（用户重点关注）
            rsi_score = 92
            rsi_penalty_factor = 0.98
        elif rsi_value < 30:  # 轻度超卖 - 基础高奖励（用户特别要求）
            rsi_score = 90
            rsi_penalty_factor = 1.0
        elif 30 <= rsi_value <= 35:  # 刚脱离超卖区域 - 仍然给予较高评分
            rsi_score = 85
            rsi_penalty_factor = 1.0
        elif 35 < rsi_value <= 45:  # 健康低位范围
            rsi_score = 80
            rsi_penalty_factor = 1.0
        elif 45 < rsi_value <= 55:  # 中性范围
            rsi_score = 70
            rsi_penalty_factor = 1.0
        elif 55 < rsi_value <= 65:  # 偏高但可接受
            rsi_score = 55
            rsi_penalty_factor = 1.1
        elif 65 < rsi_value <= 75:  # 轻度超买 - 明显惩罚
            rsi_score = 40
            rsi_penalty_factor = 1.4
            risk_factor *= 1.3
        elif 75 < rsi_value <= 85:  # 中度超买 - 严厉惩罚
            rsi_score = 20
            rsi_penalty_factor = 1.8
            risk_factor *= 1.6
        else:  # rsi_value > 85 严重超买 - 极度惩罚
            rsi_score = 8
            rsi_penalty_factor = 2.2
            risk_factor *= 2.2
        
        # 低RSI + 即将金叉的组合奖励（用户特别关注的情况 - 优化版）
        if rsi_value < 30 and pre_golden_bonus > 0:
            # 获取加速度信息
            momentum_quality = 'weak'
            diff_acceleration = 0
            if 'pre_golden_cross' in macd_info and macd_info['pre_golden_cross']['detected']:
                pre_cross_info = macd_info['pre_golden_cross']
                momentum_quality = pre_cross_info.get('momentum_quality', 'weak')
                diff_acceleration = pre_cross_info.get('diff_acceleration', 0)
            
            # 基础组合奖励
            combo_bonus = min(15, rsi_score * 0.15)  # 最多15分组合奖励
            
            # 新增：基于加速度的组合奖励放大
            if momentum_quality in ['explosive', 'strong'] and diff_acceleration > 0.005:
                # 低RSI + 高加速度即将金叉 = 黄金组合，大幅奖励
                combo_bonus *= 2.5  # 2.5倍奖励
            elif momentum_quality == 'moderate' and diff_acceleration > 0.002:
                # 低RSI + 中等加速度即将金叉 = 优质组合
                combo_bonus *= 2.0  # 2倍奖励
            elif diff_acceleration > 0:
                # 低RSI + 任何向上加速度 = 良好组合
                combo_bonus *= 1.5  # 1.5倍奖励
            
            combo_bonus = min(30, combo_bonus)  # 设置上限30分
            base_score += combo_bonus * 0.05  # 额外5%权重给组合奖励
        
        base_score += rsi_score * 0.20  # 权重20%
        
        # 3. 估值评分（权重18% - 提高估值权重，因为用户关注低估值）
        valuation_score = enhanced_analysis.get('valuation_score', 50)
        
        # 低估值 + 低RSI的组合奖励
        if rsi_value < 30 and valuation_score > 70:
            # 低估值低RSI组合，这是用户特别关注的黄金组合
            valuation_bonus = min(20, (valuation_score - 70) * 0.5)
            valuation_score += valuation_bonus
            valuation_score = min(100, valuation_score)
        
        base_score += valuation_score * 0.18  # 提高估值权重到18%
        
        # 4. 趋势强度评分（权重12% - 降低）
        trend_score = enhanced_analysis['trend_strength']
        # RSI超买时降低趋势评分的权重
        if rsi_value > 75:
            trend_score *= 0.6
        base_score += trend_score * 0.12
        
        # 5. 价格动量评分（权重8% - 进一步降低）
        momentum_score = enhanced_analysis['price_momentum']
        # RSI超买时价格动量可能是陷阱
        if rsi_value > 80:
            momentum_score *= 0.5
        elif rsi_value > 70:
            momentum_score *= 0.7
        base_score += momentum_score * 0.08
        
        # 6. 波动率控制评分（权重10%）
        volatility_score = enhanced_analysis['volatility']
        drawdown_risk_score = self._calculate_drawdown_risk()
        base_score += volatility_score * 0.06
        base_score += drawdown_risk_score * 0.04
        
        # 7. 市场结构分析（权重9%）
        support_resistance_score = enhanced_analysis['support_resistance']
        market_environment_score = enhanced_analysis['market_environment']
        base_score += support_resistance_score * 0.05
        base_score += market_environment_score * 0.04
        
        # 应用所有惩罚系数
        final_score = base_score / (risk_factor * rsi_penalty_factor)
        
        # 超买区间的额外约束：设置评分上限
        if rsi_value > 75:
            final_score = min(final_score, 70)
        if rsi_value > 85:
            final_score = min(final_score, 50)
        
        # 超买与金叉冲突检查
        if macd_info['golden_cross']['detected'] and rsi_value > 70:
            conflict_penalty = min(0.4, (rsi_value - 70) / 30 * 0.4)
            final_score *= (1 - conflict_penalty)
        
        return {
            'total_score': max(0, min(100, final_score)),
            'macd_score': macd_score,
            'rsi_score': rsi_score,
            'valuation_score': valuation_score,
            'trend_score': trend_score,
            'momentum_score': momentum_score,
            'volatility_score': enhanced_analysis['volatility'],
            'drawdown_risk_score': drawdown_risk_score,
            'support_resistance_score': enhanced_analysis['support_resistance'],
            'market_environment_score': enhanced_analysis['market_environment'],
            'pre_golden_bonus': pre_golden_bonus,  # 新增：即将金叉奖励
            'risk_factor': risk_factor,
            'rsi_penalty_factor': rsi_penalty_factor,
            'rsi_value': rsi_value
        }
    
    def generate_investment_advice(self, investment_score, macd_info, rsi_info, enhanced_analysis):
        """
        生成智能投资建议（优化版 - 特别奖励即将金叉和低估值低RSI组合）
        """
        total_score = investment_score['total_score']
        risk_factor = investment_score['risk_factor']
        rsi_value = investment_score['rsi_value']
        rsi_penalty_factor = investment_score.get('rsi_penalty_factor', 1.0)
        pre_golden_bonus = investment_score.get('pre_golden_bonus', 0)
        valuation_score = investment_score.get('valuation_score', 50)
        
        # 检查是否为用户特别关注的组合
        is_golden_combo = (rsi_value < 30 and valuation_score > 70)  # 低RSI + 高估值评分
        is_pre_golden = pre_golden_bonus > 0  # 即将金叉
        
        # 根据评分确定投资行动（优化版）
        if total_score >= 85:  # 提高强烈推荐的门槛
            action = 'strong_buy'
            action_text = '强烈推荐买入'
            position_ratio = min(85, 65 + (total_score - 85) * 1.0)  # 65-85%
            hold_period = '20-40天'  # 延长持有期
            win_probability = min(90, 75 + (total_score - 85) * 1.0)  # 75-90%
        elif total_score >= 75:
            action = 'moderate_buy'
            action_text = '中等推荐买入'
            position_ratio = min(65, 45 + (total_score - 75) * 2.0)  # 45-65%
            hold_period = '15-25天'
            win_probability = min(80, 65 + (total_score - 75) * 1.5)  # 65-80%
        elif total_score >= 65:
            action = 'cautious_buy'
            action_text = '谨慎买入'
            position_ratio = min(45, 25 + (total_score - 65) * 2.0)  # 25-45%
            hold_period = '8-18天'
            win_probability = min(70, 55 + (total_score - 65) * 1.5)  # 55-70%
        elif total_score >= 55:
            action = 'consider_buy'
            action_text = '考虑买入'
            position_ratio = min(30, 15 + (total_score - 55) * 1.5)  # 15-30%
            hold_period = '5-12天'
            win_probability = min(60, 45 + (total_score - 55) * 1.5)  # 45-60%
        elif total_score >= 45:
            action = 'cautious'
            action_text = '谨慎观望'
            position_ratio = 0
            hold_period = '暂不建议持有'
            win_probability = max(35, 55 - (55 - total_score) * 2)  # 35-55%
        elif total_score >= 35:
            action = 'hold'
            action_text = '继续持有（如有）'
            position_ratio = 0
            hold_period = '逐步减仓'
            win_probability = max(30, 45 - (45 - total_score) * 1.5)  # 30-45%
        elif total_score >= 25:
            action = 'sell'
            action_text = '建议卖出'
            position_ratio = 0
            hold_period = '立即减仓'
            win_probability = max(20, 35 - (35 - total_score) * 1.5)  # 20-35%
        else:
            action = 'avoid'
            action_text = '避免买入'
            position_ratio = 0
            hold_period = '禁止操作'
            win_probability = max(15, total_score * 0.6)  # 0-20%
        
        # 特殊奖励：用户关注的黄金组合
        if is_golden_combo:
            # 低RSI + 高估值评分的组合，给予特殊奖励
            if action in ['cautious', 'hold']:
                action = 'consider_buy'
                action_text = '低估值低RSI组合，考虑买入'
                position_ratio = 20
                hold_period = '10-20天'
            elif action == 'consider_buy':
                action_text = '低估值低RSI黄金组合，推荐买入'
                position_ratio = min(position_ratio * 1.3, 40)
                win_probability = min(win_probability + 8, 75)
            elif action in ['cautious_buy', 'moderate_buy']:
                action_text = f'{action_text}（低估值低RSI优质组合）'
                position_ratio = min(position_ratio * 1.2, 60)
                win_probability = min(win_probability + 5, 85)
        
        # 特殊奖励：即将金叉
        if is_pre_golden:
            pre_cross_info = macd_info.get('pre_golden_cross', {})
            quality = pre_cross_info.get('quality', 'low')
            
            if quality == 'high' and action in ['cautious', 'hold']:
                action = 'consider_buy'
                action_text = '高质量即将金叉，考虑买入'
                position_ratio = 18
                hold_period = '8-15天'
            elif quality in ['high', 'medium']:
                if action == 'consider_buy':
                    action_text = f'{action_text}（{quality}质量即将金叉）'
                    position_ratio = min(position_ratio * 1.15, 35)
                    win_probability = min(win_probability + 3, 70)
                elif action in ['cautious_buy', 'moderate_buy']:
                    action_text = f'{action_text}（即将金叉加成）'
                    win_probability = min(win_probability + 2, 80)
        
        # 超级组合：低RSI + 高估值 + 即将金叉
        if is_golden_combo and is_pre_golden:
            if action in ['cautious', 'hold', 'consider_buy']:
                action = 'cautious_buy'
                action_text = '超级组合：低估值低RSI即将金叉，谨慎买入'
                position_ratio = min(35, position_ratio + 15)
                hold_period = '12-25天'
                win_probability = min(win_probability + 10, 75)
            elif action in ['cautious_buy', 'moderate_buy']:
                action_text = f'{action_text}（超级组合加成）'
                position_ratio = min(position_ratio * 1.25, 70)
                win_probability = min(win_probability + 8, 88)
        
        # 增强的RSI超买约束机制（保持原有逻辑）
        if rsi_value > 70:
            # RSI超买时的特殊处理
            if rsi_value > 85:  # 严重超买
                action = 'avoid'
                action_text = '严重超买，避免买入'
                position_ratio = 0
                hold_period = '禁止操作，考虑卖出'
                win_probability = min(win_probability, 20)
            elif rsi_value > 80:  # 中度超买
                if action in ['strong_buy', 'moderate_buy']:
                    action = 'cautious'
                    action_text = 'RSI超买，谨慎观望'
                position_ratio = min(position_ratio * 0.3, 10)
                hold_period = '等待RSI回落'
                win_probability = min(win_probability, 35)
            elif rsi_value > 75:  # 轻度超买
                if action == 'strong_buy':
                    action = 'cautious_buy'
                    action_text = 'RSI轻度超买，谨慎买入'
                elif action == 'moderate_buy':
                    action = 'cautious_buy'
                    action_text = 'RSI轻度超买，谨慎买入'
                position_ratio *= 0.6
                win_probability = min(win_probability, 50)
            else:  # 70 < rsi <= 75 轻微超买
                position_ratio *= 0.8
                win_probability = min(win_probability, 60)
        
        # 风险系数调整（原有逻辑）
        if risk_factor > 1.2:
            position_ratio *= 0.7  # 高风险降低仓位
            if '天' in hold_period:
                # 缩短持有时间
                days = hold_period.replace('天', '').split('-')
                if len(days) == 2:
                    new_min = max(1, int(int(days[0]) * 0.7))
                    new_max = max(new_min, int(int(days[1]) * 0.7))
                    hold_period = f'{new_min}-{new_max}天'
        
        # RSI惩罚系数调整
        if rsi_penalty_factor > 1.0:
            position_ratio /= rsi_penalty_factor  # 根据RSI惩罚系数降低仓位
            win_probability /= min(1.5, rsi_penalty_factor * 0.8)  # 降低胜率
        
        # 生成详细分析
        analysis_details = self._generate_detailed_analysis(
            investment_score, macd_info, rsi_info, enhanced_analysis, 
            total_score, action_text, win_probability
        )
        
        return {
            'action': action,
            'action_text': action_text,
            'total_score': round(total_score, 1),
            'win_probability': round(max(10, win_probability), 1),  # 胜率下限
            'position_ratio': round(max(0, position_ratio), 1),  # 仓位下限
            'hold_period': hold_period,
            'risk_level': self._get_risk_level(risk_factor * rsi_penalty_factor),  # 综合风险
            'detailed_scores': {
                'macd_score': round(investment_score['macd_score'], 1),
                'rsi_score': round(investment_score['rsi_score'], 1),
                'trend_score': round(investment_score['trend_score'], 1),
                'momentum_score': round(investment_score['momentum_score'], 1),
                'volatility_score': round(investment_score['volatility_score'], 1),
                'drawdown_risk_score': round(investment_score.get('drawdown_risk_score', 50), 1),  # 新增
                'support_resistance_score': round(investment_score['support_resistance_score'], 1),
                'market_environment_score': round(investment_score['market_environment_score'], 1),
                'valuation_score': round(investment_score['valuation_score'], 1),
                'death_to_golden_bonus': round(self._calculate_death_to_golden_bonus(), 1)  # 新增：死叉转金叉奖励
            },
            'analysis_details': analysis_details,
            'rsi_warning': self._generate_rsi_warning(rsi_value)  # 新增：RSI警告
        }
    
    def _calculate_drawdown_risk(self):
        """
        计算回撤风险评分（新增）
        计算最大回撤和当前回撤水平，评估回撤风险
        """
        try:
            close_prices = self.data['Close']
            
            # 计算累积最大值
            cumulative_max = close_prices.expanding().max()
            
            # 计算回撤
            drawdown = (close_prices - cumulative_max) / cumulative_max
            
            # 获取最大回撤
            max_drawdown = drawdown.min()  # 最大回撤（负数）
            current_drawdown = drawdown.iloc[-1]  # 当前回撤
            
            # 回撤风险评分（回撤越小评分越高）
            max_dd_pct = abs(max_drawdown) * 100
            current_dd_pct = abs(current_drawdown) * 100
            
            # 最大回撤评分
            if max_dd_pct <= 5:  # 最大回撤5%以内
                max_dd_score = 95
            elif max_dd_pct <= 10:  # 5-10%
                max_dd_score = 85
            elif max_dd_pct <= 15:  # 10-15%
                max_dd_score = 70
            elif max_dd_pct <= 20:  # 15-20%
                max_dd_score = 55
            elif max_dd_pct <= 30:  # 20-30%
                max_dd_score = 40
            elif max_dd_pct <= 40:  # 30-40%
                max_dd_score = 25
            else:  # 40%以上
                max_dd_score = 10
            
            # 当前回撤评分
            if current_dd_pct <= 2:  # 当前回撤2%以内
                current_dd_score = 95
            elif current_dd_pct <= 5:  # 2-5%
                current_dd_score = 85
            elif current_dd_pct <= 8:  # 5-8%
                current_dd_score = 70
            elif current_dd_pct <= 12:  # 8-12%
                current_dd_score = 55
            elif current_dd_pct <= 18:  # 12-18%
                current_dd_score = 40
            elif current_dd_pct <= 25:  # 18-25%
                current_dd_score = 25
            else:  # 25%以上
                current_dd_score = 10
            
            # 综合评分（当前回撤权重更高）
            final_score = max_dd_score * 0.4 + current_dd_score * 0.6
            
            return max(0, min(100, final_score))
            
        except Exception as e:
            print(f"计算回撤风险时出错: {e}")
            return 50

    def _calculate_valuation_score(self):
        """
        计算价格估值评分（优化版 - 特别奖励低估值股票）
        基于多个估值指标综合评估当前价格是否处于低位
        优化：大幅提高低估值股票的评分，特别是配合低RSI的情况
        """
        try:
            close_prices = self.data['Close']
            current_price = close_prices.iloc[-1]
            
            # 1. 相对于历史高点的位置（越低越好）- 提高奖励力度
            historical_high = close_prices.max()
            distance_from_high = (current_price / historical_high) * 100
            
            if distance_from_high <= 25:      # 距离历史高点75%以上 - 极优低位（提高标准）
                high_score = 98
            elif distance_from_high <= 35:    # 距离历史高点65%以上 - 优秀低位
                high_score = 92
            elif distance_from_high <= 45:    # 距离历史高点55%以上 - 良好低位
                high_score = 85
            elif distance_from_high <= 55:    # 距离历史高点45%以上 - 中等低位
                high_score = 75
            elif distance_from_high <= 65:    # 距离历史高点35%以上 - 偏中位
                high_score = 60
            elif distance_from_high <= 75:    # 距离历史高点25%以上 - 偏高位
                high_score = 45
            elif distance_from_high <= 85:    # 距离历史高点15%以上 - 高位
                high_score = 30
            elif distance_from_high <= 95:    # 距离历史高点5%以上 - 很高位
                high_score = 15
            else:                            # 接近或超过历史高点 - 极高位
                high_score = 5
            
            # 2. 相对于历史低点的位置（越接近低点越好）- 大幅提高低位奖励
            historical_low = close_prices.min()
            distance_from_low = ((current_price - historical_low) / (historical_high - historical_low)) * 100
            
            if distance_from_low <= 5:        # 极接近历史低点 - 极优估值（用户特别关注）
                low_score = 100
            elif distance_from_low <= 10:     # 接近历史低点 - 极优估值
                low_score = 98
            elif distance_from_low <= 15:     # 距离低点15%以内 - 优秀估值
                low_score = 95
            elif distance_from_low <= 25:     # 距离低点25%以内 - 良好估值
                low_score = 88
            elif distance_from_low <= 35:     # 距离低点35%以内 - 中等估值
                low_score = 78
            elif distance_from_low <= 50:     # 距离低点50%以内 - 偏高估值
                low_score = 65
            elif distance_from_low <= 70:     # 距离低点70%以內 - 高估值
                low_score = 45
            elif distance_from_low <= 85:     # 距离低点85%以內 - 很高估值
                low_score = 25
            else:                            # 距离低点85%以上 - 极高估值
                low_score = 10
            
            # 3. 相对于多期均线的位置（低于均线更有价值）- 提高低位奖励
            ma20 = close_prices.rolling(window=20).mean().iloc[-1]
            ma50 = close_prices.rolling(window=50).mean().iloc[-1] if len(close_prices) >= 50 else ma20
            ma200 = close_prices.rolling(window=200).mean().iloc[-1] if len(close_prices) >= 200 else ma50
            
            # 计算相对均线位置
            vs_ma20 = (current_price / ma20 - 1) * 100
            vs_ma50 = (current_price / ma50 - 1) * 100  
            vs_ma200 = (current_price / ma200 - 1) * 100
            
            # MA位置评分（低于均线越多评分越高）- 大幅提高低位奖励
            ma_scores = []
            for vs_ma in [vs_ma20, vs_ma50, vs_ma200]:
                if vs_ma <= -25:      # 低于均线25%以上 - 极优估值（用户特别关注）
                    ma_scores.append(100)
                elif vs_ma <= -20:    # 低于均线20-25% - 极优估值
                    ma_scores.append(98)
                elif vs_ma <= -15:    # 低于均线15-20% - 优秀估值
                    ma_scores.append(92)
                elif vs_ma <= -10:    # 低于均线10-15% - 良好估值
                    ma_scores.append(85)
                elif vs_ma <= -5:     # 低于均线5-10% - 中等估值
                    ma_scores.append(75)
                elif vs_ma <= 0:      # 低于均线0-5% - 轻微优势
                    ma_scores.append(65)
                elif vs_ma <= 5:      # 高于均线0-5% - 中性
                    ma_scores.append(50)
                elif vs_ma <= 10:     # 高于均线5-10% - 轻微高估
                    ma_scores.append(35)
                elif vs_ma <= 20:     # 高于均线10-20% - 高估
                    ma_scores.append(25)
                else:                 # 高于均线20%以上 - 极高估
                    ma_scores.append(10)
            
            ma_score = np.mean(ma_scores)
            
            # 4. 交易量能分析（低位缩量是好事）
            if 'Volume' in self.data.columns:
                current_volume = self.data['Volume'].iloc[-1]
                avg_volume = self.data['Volume'].rolling(window=20).mean().iloc[-1]
                volume_ratio = current_volume / avg_volume if avg_volume > 0 else 1
                
                # 低位缩量是个好信号（说明抛压轻）
                if volume_ratio <= 0.3:      # 严重缩量 - 非常好
                    volume_score = 95
                elif volume_ratio <= 0.5:    # 明显缩量 - 好
                    volume_score = 85
                elif volume_ratio <= 0.7:    # 轻微缩量 - 较好
                    volume_score = 75
                elif volume_ratio <= 1.0:    # 正常量能 - 中性
                    volume_score = 65
                elif volume_ratio <= 1.5:    # 轻微放量 - 较差
                    volume_score = 45
                elif volume_ratio <= 2.0:    # 明显放量 - 差
                    volume_score = 30
                else:                       # 巨量 - 非常差
                    volume_score = 15
            else:
                volume_score = 65  # 没有成交量数据时给中等分
            
            # 5. 即将从死叉转金叉的奖励评分
            death_to_golden_bonus = self._calculate_death_to_golden_bonus()
            
            # 6. 新增：超低估值的额外奖励（用户特别关注的情况）
            super_low_valuation_bonus = 0
            if (distance_from_high <= 30 and distance_from_low <= 20 and 
                vs_ma20 <= -10 and vs_ma50 <= -10):
                # 同时满足：距离高点70%+、距离低点20%-、低于20日和50日均线10%+
                super_low_valuation_bonus = 15  # 额外15分奖励
            elif (distance_from_high <= 40 and distance_from_low <= 30 and 
                  vs_ma20 <= -5):
                # 较宽松的超低估值条件
                super_low_valuation_bonus = 8   # 额外8分奖励
            
            # 综合评分（调整权重，更重视低位指标）
            base_score = (
                high_score * 0.30 +      # 相对历史高点位置权重30%（提高）
                low_score * 0.35 +       # 相对历史低点位置权重35%（大幅提高）
                ma_score * 0.25 +        # 相对均线位置权重25%
                volume_score * 0.10      # 成交量能权重10%（降低）
            )
            
            # 应用各种奖励
            final_score = base_score + death_to_golden_bonus * 0.08 + super_low_valuation_bonus
            
            return max(0, min(100, final_score))
            
        except Exception as e:
            print(f"计算价格估值评分时出错: {e}")
            return 50
    
    def _calculate_death_to_golden_bonus(self):
        """
        计算即将从死叉转金叉的奖励评分
        重点奖励低估值且技术面即将好转的股票
        """
        try:
            # 确保MACD数据已计算
            if self.macd_data is None:
                self.calculate_macd()
            
            if self.macd_data is None:
                return 0
            
            macd_line = self.macd_data['MACD']
            signal_line = self.macd_data['Signal']
            histogram = self.macd_data['Histogram']
            
            current_macd = macd_line.iloc[-1]
            current_signal = signal_line.iloc[-1]
            current_histogram = histogram.iloc[-1]
            
            bonus_score = 0
            
            # 1. 检查是否处于死叉状态但即将金叉
            if current_macd < current_signal:  # 当前处于死叉状态
                # 计算MACD与信号线的距离（越接近越好）
                distance = abs(current_macd - current_signal)
                max_distance = max(abs(macd_line.max()), abs(macd_line.min()))
                relative_distance = distance / max_distance if max_distance > 0 else 0
                
                # 距离越近，奖励越高
                if relative_distance <= 0.01:      # 非常接近 - 高奖励
                    distance_bonus = 30
                elif relative_distance <= 0.02:    # 很接近 - 中高奖励
                    distance_bonus = 25
                elif relative_distance <= 0.05:    # 接近 - 中等奖励
                    distance_bonus = 20
                elif relative_distance <= 0.1:     # 较接近 - 低奖励
                    distance_bonus = 15
                else:                              # 距离较远 - 无奖励
                    distance_bonus = 0
                
                bonus_score += distance_bonus
                
                # 2. 检查MACD柱状图趋势（是否在收敛向上）
                if len(histogram) >= 3:
                    recent_histogram = histogram.iloc[-3:]
                    # 检查柱状图是否在向上收敛
                    if (recent_histogram.iloc[-1] > recent_histogram.iloc[-2] and 
                        recent_histogram.iloc[-2] > recent_histogram.iloc[-3]):
                        bonus_score += 20  # 柱状图向上收敛奖励
                    elif recent_histogram.iloc[-1] > recent_histogram.iloc[-2]:
                        bonus_score += 10  # 柱状图最近向上奖励
                
                # 3. 检查MACD线本身的趋势（是否在向上）
                if len(macd_line) >= 3:
                    recent_macd = macd_line.iloc[-3:]
                    if (recent_macd.iloc[-1] > recent_macd.iloc[-2] and 
                        recent_macd.iloc[-2] > recent_macd.iloc[-3]):
                        bonus_score += 15  # MACD线连续向上奖励
                    elif recent_macd.iloc[-1] > recent_macd.iloc[-2]:
                        bonus_score += 8   # MACD线最近向上奖励
                
                # 4. 检查是否在零轴附近（更有价值）
                if abs(current_macd) <= 0.1:  # 接近零轴
                    bonus_score += 15
                elif abs(current_macd) <= 0.2:  # 较接近零轴
                    bonus_score += 10
                elif abs(current_macd) <= 0.5:  # 一般接近零轴
                    bonus_score += 5
            
            # 5. 额外奖励：如果最近有过死叉但现在在恢复
            death_cross_info = self._detect_death_cross(macd_line, signal_line, histogram)
            if death_cross_info['detected']:
                # 检查死叉后的恢复情况
                days_since_death = len(macd_line) - 1 - self._find_crossover_index(macd_line, signal_line, 'death')
                if 1 <= days_since_death <= 10:  # 死叉后1-10天内
                    # 如果MACD在向上恢复，给予额外奖励
                    if current_histogram > histogram.iloc[-2]:  # 柱状图在改善
                        bonus_score += 10
            
            return min(100, max(0, bonus_score))  # 限制在0-100之间
            
        except Exception as e:
            print(f"计算死叉转金叉奖励时出错: {e}")
            return 0
    
    def _find_crossover_index(self, macd_line, signal_line, cross_type):
        """
        查找最近一次交叉的索引位置
        """
        try:
            for i in range(len(macd_line)-1, max(0, len(macd_line)-31), -1):
                if i == 0:
                    continue
                    
                current_macd = macd_line.iloc[i]
                current_signal = signal_line.iloc[i]
                prev_macd = macd_line.iloc[i-1]
                prev_signal = signal_line.iloc[i-1]
                
                if cross_type == 'golden':
                    if (current_macd > current_signal and prev_macd <= prev_signal):
                        return i
                elif cross_type == 'death':
                    if (current_macd < current_signal and prev_macd >= prev_signal):
                        return i
            
            return -1  # 未找到
            
        except Exception:
            return -1
    
    def _get_risk_level(self, risk_factor):
        """
        根据风险系数返回风险等级
        """
        if risk_factor <= 1.0:
            return 'low'
        elif risk_factor <= 1.5:
            return 'medium'
        else:
            return 'high'
    
    def _generate_rsi_warning(self, rsi_value):
        """
        生成RSI警告信息
        """
        if rsi_value > 85:
            return {
                'level': 'severe',
                'message': '⚠️ 严重警告：RSI高达{:.1f}，处于极度超买状态，强烈建议避免买入！'.format(rsi_value),
                'suggestion': '建议等待RSI回落到65以下再考虑买入机会'
            }
        elif rsi_value > 80:
            return {
                'level': 'high',
                'message': '⚠️ 高度警告：RSI达到{:.1f}，已进入超买区间，风险较高'.format(rsi_value),
                'suggestion': '谨慎操作，仓位不宜过重，建议等待回调'
            }
        elif rsi_value > 75:
            return {
                'level': 'medium',
                'message': '⚠️ 中度警告：RSI达到{:.1f}，接近超买区间'.format(rsi_value),
                'suggestion': '可适度参与，但需减少仓位并密切关注回调风险'
            }
        elif rsi_value > 70:
            return {
                'level': 'low',
                'message': '🔍 注意：RSI达到{:.1f}，已进入超买预警区间'.format(rsi_value),
                'suggestion': '建议降低买入仓位，做好风险控制'
            }
        else:
            return None
    
    def _generate_detailed_analysis(self, investment_score, macd_info, rsi_info, enhanced_analysis, total_score, action_text, win_probability):
        """
        生成详细分析报告
        """
        analysis = f"""【智能投资分析报告】

🏆 综合评分：{total_score:.1f}/100
🎯 投资建议：{action_text}
📊 胜率预测：{win_probability:.1f}%

🔍 优化权重评分体系：
• MACD信号强度：{investment_score['macd_score']:.1f}/100 (权重25%)
• RSI动量指标：{investment_score['rsi_score']:.1f}/100 (权重20%)
• 风险控制组合：波动率控制{investment_score['volatility_score']:.1f}/100 + 回撤风险{investment_score.get('drawdown_risk_score', 50):.1f}/100 (权重20%)
• 趋势强度评分：{investment_score['trend_score']:.1f}/100 (权重15%)
• 价格动量评分：{investment_score['momentum_score']:.1f}/100 (权重10%)
• 市场结构分析：技术位置{investment_score['support_resistance_score']:.1f}/100 + 市场环境{investment_score['market_environment_score']:.1f}/100 (权重10%)
"""
        
        # 添加MACD具体分析
        if macd_info['golden_cross']['detected']:
            analysis += f"""

📈 MACD金叉分析：
• 金叉日期：{macd_info['golden_cross']['date'].strftime('%Y-%m-%d')}
• 信号质量：{macd_info['golden_cross']['quality'].upper()}
• 位置评分：{macd_info['golden_cross']['position_score']:.1f}/100
• 共振评分：{macd_info['golden_cross']['resonance_score']:.1f}/100
• 量能评分：{macd_info['golden_cross']['volume_score']:.1f}/100
• 时效评分：{macd_info['golden_cross']['timeliness_score']:.1f}/100
"""
        
        if macd_info['death_cross']['detected']:
            analysis += f"""

⚠️ MACD死叉风险：
• 死叉日期：{macd_info['death_cross']['date'].strftime('%Y-%m-%d')}
• 风险等级：{macd_info['death_cross']['risk_level'].upper()}
• 位置风险：{macd_info['death_cross']['position_risk']:.1f}/100
• 动量风险：{macd_info['death_cross']['momentum_risk']:.1f}/100
• 量能风险：{macd_info['death_cross']['volume_risk']:.1f}/100
• 时效风险：{macd_info['death_cross']['timeliness_risk']:.1f}/100
"""
        
        # 添加风险提示
        risk_level = self._get_risk_level(investment_score['risk_factor'])
        if risk_level == 'high':
            analysis += """

🚨 高风险提示：
• 市场波动较大，建议降低仓位
• 设置严格止损，控制风险
• 密切关注市场变化，灵活调整策略
"""
        
        analysis += """

📜 投资建议总结：
• 本分析基于多维度技术指标综合评估
• 建议结合个人风险承受能力调整仓位
• 投资有风险，请谨慎决策
"""
        
        return analysis

def main():
    print("股票MACD金叉和RSI分析程序")
    print("="*40)
    
    # 获取用户输入
    symbol = input("请输入股票代码 (例如: AAPL, TSLA, 000001.SZ): ").strip()
    if not symbol:
        print("股票代码不能为空")
        return
    
    # 创建分析器实例
    analyzer = StockAnalyzer(symbol)
    
    # 获取数据
    if not analyzer.fetch_data():
        print("获取数据失败，程序退出")
        return
    
    # 计算指标
    print("正在计算MACD指标...")
    if not analyzer.calculate_macd():
        print("计算MACD失败")
        return
    
    print("正在计算RSI指标...")
    if not analyzer.calculate_rsi():
        print("计算RSI失败")
        return
    
    # 显示分析结果
    print("\n" + analyzer.get_investment_suggestion())

if __name__ == "__main__":
    main()